Tuesday, July 2, 2013

Parse JSON generated by PHP

This tutorial shows how to parse a JSON string generated by PHP. Place job.php and index.html in same folder.



File: job.php
<?php
$arr = array('name' => 'john', 'lname' => 'taylor');
echo json_encode($arr);
?>

File: index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<script>
   $.ajax({
       type : "GET",
       url : "job.php",
    }).done(function(msg) {
      var obj = jQuery.parseJSON(msg);
      alert(obj.name + " " + obj.lname);
   });
</script>
</body>
</html>
A little more complex example
File: job.php
<?php
$europe = array('country1' => 'germany', 'country2' => 'france');
$asia = array('country1' => 'japan', 'country2' => 'china');
$world = array ($europe, $asia);
echo json_encode($world);
?>
File: index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
        <body>
                <script>
                     $.ajax({
                         type : "GET",
                         url : "job.php",
                     }).done(function(msg) {
                        $("#out").text(msg)
                        var obj = jQuery.parseJSON(msg);
                        alert(obj[0].country1);
                        alert(obj[1].country2);                        
                 });
                </script>
                <div id="out">&nbsp;</div>
        </body>
</html>
And another example with array_push():
File: job.php
<?php
$arr = array();
array_push($arr, array('name' => 'john', 'lname' => 'taylor'));
array_push($arr, array('name' => 'ron', 'lname' => 'miller'));
array_push($arr, array('name' => 'mike'));
echo json_encode($arr);
?>
File: index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
 <script>
 $.ajax({
  type : "GET",
  url : "job.php",
 }).done(function(msg) {
  $("#out").text(msg)
  var obj = jQuery.parseJSON(msg);
  alert(obj[0].name);
  alert(obj[2].name);    
 });
</script>
<div id="out">&nbsp;</div>
</body>
</html>

No comments:

Post a Comment