« Sending data between JavaScript and PHP using CodeIgniter, jQuery and JSON
I am sure you would have had many situations, where you had to pass large amounts of data from PHP to JavaScript. This is a very common need, especially when you are using Ajax. I have seen code where developers would send a comma separated string and parse it out in JavaScript. While it works, the code looks ugly and you can run into many issues if the data you are passing uses the delimiter (comma). A more cleaner approach, of course, is to send data through XML. But parsing XML on the client side might be an overkill for mundane tasks. A quick, clean and simpler approach is to pass data in JSON format.
If you wonder what JSON is, here is what the JSON website says, “JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.“.
The bottom line is that it is easy for ever one!
Making an Ajax request:
jQuery comes with JSON support and even lets you use it with Ajax calls. Let us say, you have an onblur event which makes an Ajax call to get data for the rest of the fields, you would do the following in your onblur event:
url = “http://www.domain.com/mycontroller/” + isbn;
$.getJSON(url, function(json){
document.book_form.publisher.value = json.publisher;
});
For those of you, who have used jQuery before, the above code looks plausible. For the rest, the above function is making an Ajax call to the URL and the second argument, function(json) is a callback function, that gets kicked off when the browser receives the response.
JSON can pack multi dimensional arrays too; the above example is just returning a row of data back to the client.
Now, coming to CodeIgniter, here is a simple PHP function inside a CodeIgniter controller.
function addRecruiter() {
$count = $this->mrecruiter->checkDuplicate($email);
if($count > 0) {
$data['MTYPE'] = “ERROR”;
$data['MESSAGE'] = “The email address already exsists, please try a different one”;
} else {
$this->mrecruiter->addRecruiter();
$data['MTYPE'] = “SUCCESS”;
$data['MESSAGE'] = “Recruiter added successfully!”;
}
echo json_encode($data);
}
In the example above, we are echoing the encoded json data for an Ajax call from the browser. Let us know if you would like a more detailed example, we will publish it at the earliest.
Tech Force One is my web log related to technologies, I use day to day.
1
-
One commentto “Sending data between JavaScript and PHP using CodeIgniter, jQuery and JSON”
*,’ i was posting this topic on my blog too, this is really nice and interesting to my blog followers. “-~