
jQuery Post
I’ve seen quite a few people come into the CodeIgniter forums asking how to use jQuery’s built in AJAX functionality to post to a CodeIgniter function. In this tutorial I will walk you through creating the form, writing the jQuery, posting to the function, and working with handling the result. It’s actually really easy.
In this example, I’ll create a small, basic form that will allow user’s to input their username and email address into the form and submit it via AJAX. The input will be validated using the CodeIgniter form validation library, and an appropriate response will be displayed to the user.
Let’s check it out.
Creating Your Form
If you’ve ever submitted a form to a CodeIgniter controller before this should be very straight forward. If you haven’t, it’s as simple as changing the value of the action property of the form to point to the controller and function of choice.
Here, we will be submitting our form to a controller named forms and a function named submit within that controller. Easy stuff. Let’s move on to the forms controller.
Setting Up Your Controller
We’re only going to be looking at the submit function in forms controller. There are no other functions used in this tutorial. In the submit function, we will load the form validation library, set the rules for our input, run the validation, and then display the response to the user.
There is one additional constant provided in this example that is not part of the default CodeIgniter installation. The constant I am referring to is the IS_AJAX constant. This constant is used to determine whether or not the request that was received was an AJAX request, or a standard HTTP request. I have been told that this constant can be found in the CodeIgniter forums, however, I found out about it in one of Weblee’s screencasts. Simply paste this into the bottom of the constants.php file found at CodeIgniter install > application > config folder.
// Define Ajax Request
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
Now let’s get on to that submit function.
function submit() {
//load form validation
$this->load->library('form_validation');
//set form rules
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[15]');
$this->form_validation->set_rules('email', 'Email', 'required|max_length[20]|min_length[6]|valid_email');
//run form validation
$success = $this->form_validation->run();
//set username variable
$username = $this->input->post('username');
//if the validation was a success
if ((IS_AJAX && $success) || (!IS_AJAX && $success)) { echo "Congradulations {$username}, your form was accepted!"; }
//if validation failed
else { echo strip_tags(validation_errors()); }
}
You can see from the comments within the code what each portion does. When posting via AJAX, anything that is echoed, is returned back to the jQuery function. In a real world example, you would probably want to handle the result a little better by redirecting to another page if the request were not an AJAX request. The current code would only echo a response back to a blank page for a non AJAX request. If the validation fails, form validation error message is returned as HTML. Since we will be using that result in an alert dialog, I added the strip tags function to remove the paragraph tags from around the result. As mentioned, this would be handled differently in a production level app. For more information on the form validation process, check the CodeIgniter User Guide.
The jQuery
The jQuery code is also extremely short and to the point. This script will listen for the form submit event. When the event is triggered, the event object is passed in and uses the preventDefault function to stop the regular submission so that we can submit via AJAX instead. Next, it will use the built-in $.post function to submit the data to the specified location. The function accepts parameters of: url, data, callback, and request type. In this example, we were submitting the username and email fields and posting to /forms/submit. Here’s the code.
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
$.post("/forms/submit", { username: $("#username").val(), email: $("#email").val() }, function (data) {
alert(data);
});
});
});
That’s it. I think we had a little less than 30 lines total even with all the extra spacing and such.
Check out the demo here.









Twitter Updates

Thanks a bunch, you are extremely helpful in learning Codeignitor to a PHP novice like myself.
Cheers,
Montana Flynn
Really good job, which respect the MVC architecture proposed by CodeIgniter using JQuery methods.
Moreover, it allows a user to navigate without JavaScript activated, the accessibility is respected.
Thanks,
Will
This was a great read though! Thanks..
Very nice, but, if i have several forms on page how should i change the jquery code?
Thanks a lot, i hope you will help me, i really apreciate.
@Justme: Hey man! Have you solved your problem?
And I’ve got only another question… If I want to put the files in a database, respecting the MVC patter I supposed to use a model to do that, but with jQuery shall i send those data straight with it?
Thanks in advance for the help!
Thanks for your post! How can you deal with this error: uncaught exception: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIXMLHttpRequest.open]” nsresult: “0×80070057 (NS_ERROR_ILLEGAL_VALUE)” location: “JS frame :: http://localhost/mysite/js/jquery.js :: anonymous :: line 4389″ data: no]. That’s what i got when clicked on submit button. Please help me with that!
i like this tutorial thanks
Goog job. Just One thing: use jQuery’s serialize function for collecting data from the from. With this solution you don’t have to manipulate your submit code when you want to use it for other forms.
You have to change the title to “The EASIEST AJAX Post with jQuery and CodeIgniter”
u r a god!
thanks.