13 November, 2010

Jquery Ajax in CodeIgniter

The time I first started coding in codeIgniter, i had lots of confusions regarding
how to implemente ajax in codeigniter. I was using jquery for a project in codeIgniter,
and had a need to use jquery ajax in different sections of my project.
Since codeIgniter is MVC supportive open source framework, implementation of ajax in it is similar to usage of
ajax in other PHP MVC frameworks.
Here is how i started using ajax in codeigniter.
CodeIgniter has Model, Controller and Views (MVC).
So i started with a view file, user_notifications.php
//I had used jquery library for javascript,
//as this is one of the library I am confortable with
//include the jquery library script

function add_note() {
var note = $("#txtNote").val(); // this note value is from input type text with id as txtNote
if(note != "") {
//call the ajax function of jquery to post data to controller funcition
$.ajax({
type: "POST",
url: "user/members/add_note",
data: "&userId="+userId+"&add_user_note="+note,
success: function(responseTxt) {
alert(responseText);
return false;
}
});
}
return false;
}
....
....
in the view file we might have



In above code we are posting data using jqurey ajax function to a url specified in "url" variable
base_url() in codeigniter returns site's base URL as defined in config.php file
"user" is the folder name
"members" is the name of controller we are posting data to and
"add_note" is the function name in members controller

Now lets create a controller, members.php inside user folder

function add_note() {
//get the post data
$user_id = $this->input->post("userId");
$note_add = $this->input->post("add_user_note");
//add this note to database or process like you want
//the return successful or error message or something else that you want to, like
echo "Note Added Successfully...!";
}

The last echo message will be displayed by alert inside success function, with the message
passed from controller function as return as responseText.
So in this way we can use ajax with codeigniter.

No comments: