18
Apr

Send and receive objects using JSON, AJAX, jquery and PHP

Recently I was working on a client-side project that sent a parameter to the server via AJAX and received some data back. If you just want a string returned from the server then this is nothing new and easily done with jquery and AJAX (I think there are resouces on the web. I’ll write another tutorial soon.)

But what if you need more than a string to be returned from the server? What if the information you receive back from the server requires an object or you’d like to receive more than one parameter?

jQuery and JSON make this very easy.

First the jQuery. I’m going to use the ‘ajax’ function as you can incorporate a ‘beforeSend’ parameter. This tells your client to expect a JSON response and is necessary to prevent problems with some clients. In theory there’s no reason why you couldn’t use the simpler ‘get’ / ‘post’ or ‘getJSON’ functions but clients can be very finicky with this type of response and I’ve encountered bugs with getJSON in IE (suprise) that were very difficult to debug and were solved with the code below.

For this example I’m going to send a URL to the server and get back some information about that URL. I want two pieces of information back from the server: a boolean true / false and a string with more information regarding this result.

Let’s send a name / value pair to send to the server. You can create a JSON object or just use:


var postData ="domain=techcrunch.com";

So I’m sending a request to the server with name ‘domain’ and value ‘techcrunch.com’ (best I could think of on short notice).

Here is the jQuery to do this:


var postData ="domain=techcrunch.com";

 $.ajax({
    type: "POST",
    dataType: "json",
    data: postData,
    beforeSend: function(x) {
        if(x && x.overrideMimeType) {
            x.overrideMimeType("application/json;charset=UTF-8");
        }
    },
    url: 'testURL.php',
    success: function(data) {
        // 'data' is a JSON object which we can access directly.
        // Evaluate the data.success member and do something appropriate...
        if (data.success == true){
            $('#section1').html(data.message);
        }
        else{
            $('#section2').html(data.message);
        }
    }
});

Obviously we’re sending a POST request to ‘testURL.php’. Note the datatype and beforesend parameters. The ‘beforesend’ function, as mentioned before, is to deal with quirks on some clients. The interesting thing is the ‘data’ object that is returned from the server with two members: success (boolean) and message (string). You can access them directly using data.success and data.message. This is a simple example but you can of course receive just about anything in your JSON object: arrays, strings, booleans; even other objects. [edit: PHP's json_encode() does *not* work well with nested associative arrays. I've found you pretty much have to write your own JSON encoder / decoder for complex arrays].

Ok so this gets sent off to the server where we receive the ‘domain’ as a POST argument. We do our processing and want to send back the result (which needs to be in JSON format). Luckily PHP has a function which makes it very easy to do this: json_encode . Couldn’t be easier: set up an associative array and then call json_encode on it:


// Here's the argument from the client.
$domain = $_POST['domain'];

// Do lots of devilishly clever analysis and processing here...
$success = processDomain($domain);

if ($success == true){

	// Set up associative array
	$data = array('success'=> true,'message'=>'Success message: hooray!');

	// JSON encode and send back to the server
	echo json_encode($data);
}
else{
	// Set up associative array
	$data = array('success'=> false,'message'=>'Failure message: boo!');

	// JSON encode and send back to the server
	echo json_encode($data);
}

That’s it! Easy! Be aware that the formatting of JSON objects can be very strict regarding single / double quotes, etc. You can read more here: json.org

About James
I'm all-round developer with a background in enterprise development using C++. I'm a client and server side web developer with a particular interest in making the web as interesting and usable as possible with seamless client / server interaction using jQuery and AJAX.

20 Comments for this entry

Stéphane
January 29th, 2012 on 7:16 am

Useful… thanks!

Ashish
March 23rd, 2012 on 1:21 am

Helped. Thanks.

George
May 15th, 2012 on 5:15 am

Very nice.
Accomplished the same result in a similar way , minutes before reading this.
Very helpful !!!

pratibha parimoo
May 17th, 2012 on 2:08 pm

Thanks for sharing

Ross Marks
August 30th, 2012 on 10:20 am

thank you so so much, just saved me from 2+ hours headache – bloody ajax! :p

kingsley
October 17th, 2012 on 8:28 am

You rock budddyyyyy……… thanks alooooooooooooottttttttt………

nrm
November 21st, 2012 on 4:23 am

Really helpful… Thanks :)

darkC0de
November 29th, 2012 on 11:52 am

Finally a good article.

Harold_CH
December 6th, 2012 on 8:51 am

Muchas, pero muchas gracias brother. Mas claro y directo no podia ser . . .

garfield
December 12th, 2012 on 2:53 pm

best way:

die(json_encode($data));

silvinagreta
December 14th, 2012 on 3:34 am

Exactly what I was looking for for the last half hour. Thanks!!

ravikant
January 9th, 2013 on 9:28 pm

Thanks..a lot ..

Ko Aung
January 26th, 2013 on 2:59 am

Thank you. This is useful for me.

saeed
February 5th, 2013 on 5:05 am

thankful

nimesh jain
February 7th, 2013 on 7:11 pm

thanx bro. That really helped. Couldn’t have guessed ‘beforeSend’ would do the trick. Thanx

Naagar
February 27th, 2013 on 12:33 am

good one

ajinkya
April 9th, 2013 on 9:35 am

Thank you for this very nice explanation .

Rasel Ahmed
April 16th, 2013 on 4:07 am

Thank you boss, So helpful

aZIN
July 8th, 2013 on 3:19 pm

Great. Thanks a lot, it really helped me.

Nitin
January 20th, 2014 on 3:04 am

Good One !!

2 Trackbacks / Pingbacks for this entry

Send and receive objects using JSON, AJAX, jquery and PHP | RefreshTheNet, April 23rd, 2010 on 5:30 am

[...] Send and receive objects using JSON, AJAX, jquery and PHP [...]

links for 2010-06-14 | Michael Ong | On9 Systems, June 14th, 2010 on 5:12 pm

[...] Send and receive objects using JSON, AJAX, jquery and PHP (tags: json ajax php) [...]