jQuery JSON with PHP json_encode and json_decode

Today I looked for a replacement for my old jspanserializer.js script that I can’t even remember where I found anymore. Turns out that I wont have to either, I can forget it. From now on I’ll use jQuery JSON instead.

This stuff can really not get any simpler than this:

<html>
<head>
<title>Json Test</title>
<SCRIPT src="jquery.js"></SCRIPT> 
<SCRIPT src="jquery.json.js"></SCRIPT> 
<script>
$(document).ready(function(){
  var data = new Object();
  data.hello = "Hello";
  data.world = 'World';
  data.worked = " it worked ";
  data.somebool = true;
  data.array = new Array("he\"ll\"o", '"World"');
  var dataString = $.toJSON(data);
  $.post('phpfile.php', {data: dataString}, function(res){
    var obj = $.evalJSON(res);
    if(obj.somebool === true)
      $("#result").html(obj.hello + ' ' + obj.array[1] + obj.worked + ". Message from PHP: "+obj.php_message);
  });
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>

We initialize some test data, encode it with $.toJSON and send it with $.post to phpfile.php:

$res = json_decode($_REQUEST['data'], true);
$res["php_message"] = "I am PHP";
echo json_encode($res);

Note the last argument to json_decode, omitting it will result in a return type of stdObject which is not what we want in this simple test. Note that json_decode requires PHP 5.2. If that is not available you might want to check out an alternative method.

And the final output in the result div:

Hello "World" it worked . Message from PHP: I am PHP

Great!

  • Digg
  • del.icio.us
  • blogmarks
  • Reddit
  • Simpy
  • StumbleUpon
  • Technorati
  • description
  • Ma.gnolia
  • Slashdot
  • Sphinn
  • Spurl

Related Posts

Sponsored links

Top Search Engine Rankings
Free Recipes

Tags: , , ,

Posts linking to this article:

Links roundup August 19th 2008
I had forgotten to update this week's weekly roundup post before it auto published at midday yesterday so missed adding a bunch of additional offsite links. This follow up post contains the ones I missed plus some additional ones from ...

prodevtips.com: jquery json with php json_encode and json_decode
on the prodevtips blog, henrik shows an example of the "perfect combination" of php's json functionality and a powerful javascript library, jquery. read more.

Subscribe with Google Reader