Design a data table using jQuery to implement Ajax Functions

Source: Internet
Author: User

At present, jQuery and PHP are undoubtedly excellent cooperation in Web development. Among them, PHP is easy to use and popular with developers. jQuery is flexible, simple, and powerful in front-end development, which can provide a lot of dazzling results. In the previous article, we mainly talked about the design of the table base class. This article will mainly introduce the testing and running sections, as well as adding AJAX functions to integrate jQuery.

Test Run

Now, we can test and test the effectiveness of the data table Assistant class we wrote in CI. Before testing, create a data table in MYSQL as follows:

 
 
  1. CREATE DATABASE `dg_test`;  
  2. CREATE TABLE `users` (  
  3. `id` int(11) NOT NULL AUTO_INCREMENT,  
  4. `username` varchar(80) NOT NULL,  
  5. `password` varchar(32) NOT NULL,  
  6. `email` varchar(255) NOT NULL,  
  7. UNIQUE KEY `id` (`id`)  
  8. ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; 

Insert some initial data

 
 
  1. INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES  
  2.  (1, 'david', '12345', 'david@domain.com'),  
  3.  (2, 'maria', '464y3y', 'maria@domain.com'), (3, 'alejandro', 'a42352fawet', 'alejandro@domain.com'),  
  4. (4, 'emma', 'f22a3455b2', 'emma@domain.com' 

Next, write the control layer test file named test. php and save it in the application/controller directory. The Code is as follows:

 
 
  1. class Test extends CI_Controller{  
  2. function __construct(){  
  3. parent::__construct();  
  4. $this->load->helper(array('datagrid','url'));  
  5. $this->Datagrid = new Datagrid('users','id');  
  6. }  
  7. function index(){  
  8. $this->load->helper('form');  
  9. $this->load->library('session');  
  10. $this->Datagrid->hidePkCol(true);  
  11. $this->Datagrid->setHeadings(array('email'=>'E-mail'));  
  12. $this->Datagrid->ignoreFields(array('password'));  
  13. if($error = $this->session->flashdata('form_error')){  
  14. echo "$error";  
  15. }  
  16. echo form_open('test/proc');  
  17. echo $this->Datagrid->generate();  
  18. echo Datagrid::createButton('delete','Delete');  
  19. echo form_close();  
  20. }  
  21. function proc($request_type = ''){  
  22. $this->load->helper('url');  
  23. if($action = Datagrid::getPostAction()){  
  24. $error = "";  
  25. switch($action){  
  26. case 'delete' :  
  27. if(!$this->Datagrid->deletePostSelection()){  
  28. $error = 'Items could not be deleted';  
  29. }  
  30. break;  
  31. }  
  32. if($request_type!='ajax'){  
  33. $this->load->library('session');  
  34. $this->session->set_flashdata('form_error',$error);  
  35. redirect('test/index');  
  36. } else {  
  37. echo json_encode(array('error' => $error));  
  38. }  
  39. } else {  
  40. die("Bad Request");  
  41. }}  
  42.  }  
  43.  ?> 

The following is a brief analysis of this test file. First, in its constructor, load the written datagrid data table helper file and the url helper class in the CI, and

 
 
  1. $this->Datagrid = new Datagrid('users','id'); 

Initialize the construction method of the Data Assistant class, specify the table name as users, and the data column as id. Then

 
 
  1. $this->Datagrid->setHeadings(array('email'=>'E-mail')); 

Set the header to be displayed and display the email as email. And pass

 
 
  1. $this->Datagrid->ignoreFields(array('password')); 

If this parameter is set, the password column is not displayed in the data table "G. Next, call the generate () method to generate a table. In the proc () method, the user is responsible for processing the selected and deleted records, while in the if ($ request_type! = 'Ajax '){......} In this Code, it determines whether it is an ajax call. If it is not an ajax call, an error message is returned normally. Otherwise, an error message is returned using the json_encode method, this technique is also very common. The purpose of this technique is to satisfy both ajax and non-ajax calls.

The final running effect is as follows:

Integrate jQuery with AJAX Functions

Now we can add the AJAX function for it, so we need to integrate jQuery. Because this document is not a beginner's tutorial, it will not explain jQuery knowledge, but will explain how to integrate it directly. Create a new folder named js, place the jQuery library file in it, and create a new user. php file. The Code is as follows:

 
 
  1.    <title>Users Management</title> 
  2.    <script src="<?php echo base_url(); ?>js/jquery-1.6.3.min.js"></script> 
  3.    <script src="<?php echo base_url(); ?>js/datagrid.js"></script> 
  4. <body> 
  5. <?php 
  6.       $this->Datagrid->hidePkCol(true);  
  7.       if($error = $this->session->flashdata('form_error')){  
  8.          echo "<font color=red>$error</font>";  
  9.       }  
  10.       echo form_open('test/proc',array('class'=>'dg_form'));  
  11.       echo $this->Datagrid->generate();  
  12.       echo Datagrid::createButton('delete','Delete');  
  13.       echo form_close();  
  14. ?> 
  15. </body> 

Because ajax is used to determine which records in the table are selected and respond to the delete button event, only the above php code is retained, create a js/datagrid In the js directory. js file, you also need to modify the index method in the previous section as follows:

 
 
  1. function index(){  
  2. $this->load->helper('form');  
  3. $this->load->library('session');  
  4. $this->load->view('users');  
  5.  } 

You can also modify the relevant CSS styles, for example:

 
 
  1. .dg_form table{  
  2. border:1px solid silver;  
  3. }  
  4. .dg_form th{  
  5. background-color:gray;  
  6. font-family:"Courier New", Courier, mono;  
  7. font-size:12px;  
  8. }  
  9. .dg_form td{  
  10. background-color:gainsboro;  
  11. font-size:12px;  
  12. }  
  13. .dg_form input[type=submit]{  
  14. margin-top:2px;  
  15.  }  

In datagrid. js, add the following function methods:

 
 
  1. $ (Function (){
  2. $ ('. Dg_form: submit'). click (function (e ){
  3. E. preventDefault ();
  4. Var $ form = $ (this). parents ('form ');
  5. Var action_name = $ (this). attr ('class'). replace ("dg_action _","");
  6. Var action_control = $ ('');
  7. $ Form. append (action_control );
  8. Var post_data = $ form. serialize ();
  9. Action_control.remove ();
  10. Var script = $ form. attr ('action') + '/ajax ';
  11. $. Post (script, post_data, function (resp ){
  12. If (resp. error ){
  13. Alert (resp. error );
  14. } Else {
  15. Switch (action_name ){
  16. Case 'delete ':
  17. // Remove deleted data from the data table
  18. $ Form. find ('. dg_check_item: checked'). parents ('tr'). remove ();
  19. Break;
  20. Case 'anotheraction ':
  21. ..
  22. Break;
  23. }
  24. }
  25. }, 'Json ')
  26. })
  27. })

In the above Code, first use var $ form = $ (this). parents ('form'); to obtain the form name, and then use

 
 
  1. var action_name = $(this).attr('class').replace("dg_action_","") 

Obtain the action name, while

 
 
  1. var action_control = $('');  
  2. $form.append(action_control);  

The hidden domain action_control is dynamically generated and added to the form through $ form. append (action_control.

Next, we will send the client data to the server through $. post (script, post_data, function (resp). The script variable defines the path for ajax sending,

Post_data is the form data serialized by $ form. serialize. Then, in the return value of the callback function, check whether the resp contains the error message. If the returned value contains the error message, use alert to display the information, and then use

 
 
  1. $form.find('.dg_check_item:checked').parents('tr').remove(); 

A piece of code to remove deleted data rows from the server in the data table.

Finally, add the following code:

 
 
  1. $('.dg_check_toggler').click(function(){  
  2. var checkboxes = $(this).parents('table').find('.dg_check_item');  
  3. if($(this).is(':checked')){  
  4. checkboxes.attr('checked','true');  
  5. } else {  
  6. checkboxes.removeAttr('checked');  
  7. }  
  8. })  

This Code indicates that when you select the "select all" button in the table, the checkbox before all records in the table (stored in the variable checkboxes) will be searched ), then, if you have checked all the records in the checkbox box, you can use jQuery to set the attr attribute of the checkbox before all the records to true, that is, you can select all the records, and vice versa.

Summary

This article uses the famous php development framework CI and jQuery to guide readers on how to build a common data table help class and has ajax functions (implemented by jQuery ). You can learn a lot about the CI framework and jQuery skills and knowledge.

Original article: http://tech.it168.com/a2011/1027/1264/000001264981_all.shtml

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.