title: JSON PHP Javascript - Simple Working Example
body: <p>HI,</p>
  
  <p>I am using the following code</p>
  
  <p><strong>request.js</strong></p>
  
  <pre><code>var request;
  function runAjax(JSONstring)
  {
  
      // function returns "AJAX" object, depending on web browser
      // this is not native JS function!
      request = new XMLHttpRequest();
  
      request.open("GET", "request.php?json="+JSONstring, true);
      request.onreadystatechange = sendData;
      alert('called');
      request.send(null);
  }
  
  function sendData()
  {
      // if request object received response
      if(request.readyState == 4)
      {
      // parser.php response
      var JSONtext = request.responseText;
      // convert received string to JavaScript object
    try
    {
    //var JSONobject = eval('(' + JSONtext + ')');
      var JSONobject = JSON.parse(JSONtext);
    }
    catch(e)
    {
      var err="Error: "+e.description;
      alert(err);
    }
   alert('1');
      // notice how variables are used
    try {
  
      var msg = "Number of errors: "+JSONobject.errorsNum+        "\n- "+JSONobject.error[0]+     "\n- "+JSONobject.error[1];
  
      alert(msg);
    }
    catch(ee)
    {
      var errr="Error: "+ee.description;
      alert(errr);
    }
      }
  }
  </code></pre>
  
  <p>The php function I have used here is <strong>request.php</strong></p>
  
  <pre><code>&lt;?php
  
  // decode JSON string to PHP object
  $decoded = json_decode($_GET['json']);
  
  // do something with data here
   echo "Decoded string - ". $decoded;
  // create response object
  $json = array();
  $json['errorsNum'] = 2;
  $json['error'] = array();
  $json['error'][] = 'Wrong email!';
  $json['error'][] = 'Wrong hobby!';
  
  // encode array $json to JSON string
  $encoded = json_encode($json);
  
  
  // send response back to index.html
  // and end script execution
  die($encoded);
  
  ?&gt;
  </code></pre>
  
  <p>I'm calling this JavaScript function from a HTML page <strong>request.html</strong></p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;script src="request.js"&gt;
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;a href="Javascript:runAjax('vinoth')"&gt;call&lt;/a&gt;&lt;br&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>The problem here is I was getting <strong>Syntax Error</strong> at the line:24</p>
  
  <pre><code>var JSONobject = JSON.parse(JSONtext);
  </code></pre>
  
  <p>if I was using </p>
  
  <pre><code>var JSONobject = eval('(' + JSONtext + ')');
  </code></pre>
  
  <p>I was getting <strong><em>" ) Expected Error "</em></strong></p>
  
  <p><em>After that I deleted browser cache. Restarted the browser, now the code seems working very fine.</em></p>