Learning Objectives
In Part 4 you will learn:
- How to perform Ajax based CREATE operation.
- How to switch jQuery tab programmatically.
Previous Parts
Modify Model
Add following method in mUsers class.
1 2 3 4 5 6 7 8 | public function create() { $data = array( 'name' => $this->input->post( 'cName', true ), 'email' => $this->input->post( 'cEmail', true ) ); $this->db->insert( 'users', $data ); } |
Above method is very simple. On line 2, data array is created containing name and email values. Then on line 7, insert active record method is called to insert a new record in users table.
The column names of table as defined in database must match the key names defined in data array. For example on line 3, ‘name’ must match the column name of users table in database otherwise this value won’t be inserted.
Modify Controller
Add create method in Home controller class.
1 2 3 4 5 6 | public function create() { if( !empty( $_POST ) ) { $this->mUsers->create(); echo 'New user created successfully!'; } } |
This method only calls create method of mUsers model if $_POST array is not empty. Then it echoes a success message.
Modify View
You need to add a form in a div having id “create” as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <div id="tabs"> <ul> <li><a href="#read">Read</a></li> <li><a href="#create">Create</a></li> </ul> <div id="read"> <table id="records"></table> </div> <div id="create"> <form action="" method="post"> <p> <label for="cName">Name:</label> <input type="text" id="cName" name="cName" /> </p> <p> <label for="cEmail">Email:</label> <input type="text" id="cEmail" name="cEmail" /> </p> <p> <label> </label> <input type="submit" name="createSubmit" value="Submit" /> </p> </form> </div> </div> <!-- end tabs --> |
“create” div is right after the “read” div. There I added a new form containing “cName” and “cEmail” input text fields. Also note that I didn’t used the id and name of input fields as “name” and “email”. It’s done to prevent id and name collision because both of the attributes must be unique in an html page. I gave the id and name of input fields in update form as “name” and “email”.
Modify CSS
Add the following CSS in styles.css file.
#create label { display: inline-block; text-align: right; width: 60px; }
Modify Javascript
The Read Function
First create a new function containing code to perform a READ Ajax call because later you will see that we need to use READ Ajax call at more than one place. So to avoid duplicate code, I am creating readUsers function.
Now open all.js file from source files of Part 3 and create a new function readUsers at the end of all.js file. Then cut the code from line 13 to 31 (in all.js) and paste it inside the readUsers function as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | ... }); //end document ready function readUsers() { //display ajax loader animation $( '#ajaxLoadAni' ).fadeIn( 'slow' ); $.ajax({ url: readUrl, dataType: 'json', success: function( response ) { for( var i in response ) { response[ i ].updateLink = updateUrl + '/' + response[ i ].id; response[ i ].deleteLink = delUrl + '/' + response[ i ].id; } //clear old rows $( '#records' ).html( '' ); //append new rows $( '#readTemplate' ).render( response ).appendTo( "#records" ); //hide ajax loader animation here... $( '#ajaxLoadAni' ).fadeOut( 'slow' ); } }); } // end readUsers |
There’s only one new line in the above READ Ajax call. On line 19 of above code snippet, I cleared the innerHTML of #records table to remove the old rows.
Now on line 13 of all.js file, simply call readUsers function like this:
readUsers();
Move Variables
You may have noted that the readUrl variable used in READ Ajax call is declared in document ready block. So it’s not accessible from readUsers function. So cut all the variables out of that block and paste it at the top of all.js file as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 | var readUrl = 'index.php/home/read', updateUrl = 'index.php/home/update', delUrl = 'index.php/home/delete', delHref, updateHref, updateId; $( function() { $( '#tabs' ).tabs({ fx: { height: 'toggle', opacity: 'toggle' } }); ... |
CREATE Ajax Call
Now make a READ Ajax call which will send the form data in create form to server using POST method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | ... // --- Create Record --- $( '#create form' ).submit( function() { $( '#ajaxLoadAni' ).fadeIn( 'slow' ); $.ajax({ url: 'index.php/home/create', type: 'POST', data: $( this ).serialize(), success: function( response ) { $( '#msgDialog > p' ).html( response ); $( '#msgDialog' ).dialog( 'option', 'title', 'Success' ).dialog( 'open' ); //clear all input fields in create form $( 'input', this ).val( '' ); //refresh list of users by reading it readUsers(); //open Read tab $( '#tabs' ).tabs( 'select', 0 ); } }); return false; }); ... |
Note the selecter “#create form” used on line 3 of above code snippet. It means select a form inside an element having id “create” and then sumbit handler is binded with the form. The submit handler runs when Submit button is clicked in the form.
On line 9, form input values are serialized in a name-value pairs seperated by & like this: “name=xyz&email=xyz@test.com”. Also note that the keyword “this” actually refers to form inside div having id “create”.
On line 12, response received from server is placed in p element in msgDialog.
On line 13, title of msgDialog is set to “Success” and the dialog box is opened.
On line 16, values of all input fields are cleared.
On line 19, READ operation is performed to get the fresh list of users. Now you may realized I moved the code of READ Ajax call in a function to prevent code duplication.
On line 22, Read tab is opened. Now the second parameter passed to tabs() method is 0. It’s because the Read tab is on index zero.
Finally on line 26, false is returned to prevent default behavior of Submit button i.e the postback.
Review
In this part, you learned how to perform a READ Ajax call. You also learned how to switch jQuery tab without user interaction. Rest of the things were already covered in previous parts. So nothing new here.
In the next part I will show you how to validate the form.
Cool.. I was waiting for ur next post
Thank you very much for sharing such interesting article. I was thinking about, how it would be if we integrate JQGrid into this? Now only thing remaining is Sorting & Paging
In the next part I will cover form validation before sorting and paging
that’s nice, then I will try some r&d on JQGrid here
Thanks!
I appreciate you going through this. I am looking forward to the next parts including validation, sorting, and paging. Once again thanks for your effort.
WBR
is there any demos?
is source file the complete version till now?
No there’s not demo. I am sorry for that.
Yes source files contain the whole project with progress till Part 4.
Thank you for these articles! They have been very helpful. I look forward to your next ones. I’m going to assume that you will use the validation helper?
Your welcome
Yes I will use validation plugin
Just curious, I’m trying to go ahead and write my own, but I really like your methods and process flow. Will you be using jQuery’s validation method alongside with CodeIgniter? I assume jQuery alone is local so using ajax+CI would make it validate server-side. I managed to make the server return an error, but how would ajax know of this error? Or would you have to parse out .response?
I will validate using only jQuery. This tutorial will focus mostly on client side. So I will not be covering Codeigniter Validation Helper.
Thanks Fawad for these tutorials, they are easy to follow and your explanations are excellent.
When I got to the create part, I just get the Ajax loading and nothing happens. I thought maybe I had a typo or something so I downloaded the source files and replaced mine . . . same thing.
Is anyone else having a problem, or might suggest why the create isn’t working?
Cheers, Bob
Ok I will test it again and reply asap
Thank your very much for this tutorial, it helps me a lot.. Godbless..
thank you man its so great, i learnd a lot about jquery+ci