Sharing JSON data between jQuery and PHP using Ajax

Posted at February 05, 2012

When building interactive websites I often find the need to send or receive data after a page load. Ajax is the perfect solution for this problem, as it permits data sharing between the front end (javascript) and the backend (PHP) in the background.

Why would I need Ajax?
When you you start using Ajax it opens endless possibilities for your website, think about autoupdating a page (timing), showing specific content on a click or adding new content on a scroll (for example when scrolled to the bottom), or logging details (think Google Analytics).

When you use jQuery you can use a couple of very powerful build in functions to make Ajax a breeze.

Sending data from jQuery to PHP

When you need to send data to your backend you can use either POST or GET, POST (as the name implies) is preferred here because of browser caching. Here is an example of a POST call on my website that logs information about this site visitors.

$.post("track/", obj);

As you can see the function is really simple to use. The first parameter is the url where the ajax request will go to. Make sure this points to your PHP script that should process the data.

_One tip that might save you a full day of headaches: when you’re using Apaches’ mod_rewrite make sure that this url doesn’t get redirected (adding a / for example), you will lose the POST data._

The second parameter is the data to send, which is always an javascript object. Instead of the var obj you could also put a literal object in there like so:

$.post("track/", { dog: 'Buddy', legs: 4 });

On the backend you can now grab all the data you need in POST format like you would when working with forms.

$dog = $_POST['dog'];

In this simple example all PHP output is ignored.

Note that this is the most semantically correct way of using POST. If you are worried about performance you should use GET to send data (up to 2k of it). This is because ajax POST calls are send in two parts, the header and the content.

Sending data from PHP to jQuery

Due to the way Ajax works, javascript always send an Ajax request on which the server can respond with output. This means that you have to start with the javascript again. This time we use GET so the browser could potentially cache the response.

This code snippet is from from my blog overview where I dynamically fetch other post pages.

$.getJSON(link, function(data) {
   $blogPosts.stop().animate({ /* (…) */}, speed, function() {
      // (…)
      var nav = ";
      if(data.previousPage) nav += '+ data.jsonPrevious + '">< oudere posts';
      if(data.nextPage) nav += '+ data.jsonNext + '" class=right>nieuwere posts >';

It all starts with the getJSON function, which not only does a GET request for content, but also parses all output to JSON (safely). The link (first parameter) is yet again the path to the PHP script.

The second parameter is a callback function which should be executed as soon as the data comes in. The data parameter of this function is all the output in a javascript object (called data).

It’s very easy to write a PHP script that outputs JSON. Just stuff up an array and run it trough json_encode like so.

$result['dog'] = 'Buddy';
$result['legs'] = 4;

echo json_encode($result);

which will output:


There are a lot more advanced things you can do with the jQuery ajax functions, but I think this covers the basics. For more details check out the functions $.post and $.getJSON

Posted at February 05, 2012, under jQueryPHP.