jQuery JSON with PHP json_encode and json_decode


Update: There is now a real world example called Shortening multiple URLs with jQuery, PHP, picolisp and bit.ly, you might want to check it out when you’re done here. It uses jQuery JSON extensively. Another one is Multiple select lists with jQuery and JSON.

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!

Related Posts

Tags: , , ,