Getting Started with JSON's and php

Getting Started with JSON's and php

I had been using xml for a while now. At the beginning of the week I had an idea to send data as a  string in a format like a javascript object. I didn't know it was called a JSON. The next day I was reading through lxer (a linux news site) and came across an article on using php with XML or JSON. Since I didn't know what a JSON was I looked it up. Wow just what I wanted to use. It only talked about using it from a file where as I wanted to use it more like ajax. I was looking around for documentation on this and found a bunch of misinforming articles. I put together some tests and I think I have a good working example.

  1. <?php if(count($_REQUEST)==0){?><!DOCTYPE html>
  2. <html>
  3.  <head>
  4.   <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
  5.   <title>JSON TEST</title>
  6.   <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
  7.   <script>
  8. $(function()
  9. {var arr=new Array('one','two','three');
  10.  data={'arr':arr}
  11.  $.ajax(
  12.   {
  13.    dataType:'json',/* Expected return type (seen bad documentation out there saying to set this as POST)*/
  14.    type:'post',/* How it is sent POST or GET */
  15.    data:'json='+JSON.stringify(data),/* Because php expects POST or GET data to be in a form like this name=value */
  16.    success:parse
  17.   });
  18. });

  19. function iterate(arr)
  20. {var html='';
  21.  $(arr).each(function(i,val)
  22.  {html+=','+val;
  23.  });
  24.  return html;
  25. }
  26.  
  27. function iterate_2(arr)
  28. {var html='';
  29.  $.each(arr,function(i,val)
  30.  {html+=','+val;
  31.  });
  32.  return html;
  33. }
  34.  
  35. function iterate_for(arr)
  36. {var html='';
  37.  for(var i=0;i<arr.length;i++)
  38.  {html+=','+arr[i];
  39.  }
  40.  return html;
  41. }
  42.  
  43. /*Wow I can use a returned json object without parsing so cool? */
  44. function parse(json)
  45. {var html='';
  46.  html+=iterate_for(json['arr']);
  47.  html+=iterate(json.arr); 
  48.  html+=iterate_2(json['more']['arr']); 
  49.  $('body').html($('body').html()+html)
  50. }
  51.   </script>
  52.  </head>
  53.  <body>
  54. JSON TEST
  55.  </body>
  56. </html>
  57. <?php exit();}
  58. $test=array();
  59. $test['arr']=array('one','two','three');
  60. /*Parse a json object making it into a php object*/
  61. $json=json_decode($_REQUEST['json']);
  62. $json->more=$test;
  63. /*Return a JSON object*/
  64. header('Content-Type: text/javascript; charset=utf-8');
  65. echo json_encode($json,JSON_PRETTY_PRINT);
  66. ?>