views:

56

answers:

1

HI,

I am using the following code

request.js

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);
  }
    }
}

The php function I have used here is request.php

<?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);

?>

I'm calling this JavaScript function from a HTML page request.html

<html>
<head>
<script src="request.js">
</script>
</head>
<body>
<a href="Javascript:runAjax('vinoth')">call</a><br>
</body>
</html>

The problem here is I was getting Syntax Error at the line:24

var JSONobject = JSON.parse(JSONtext);

if I was using

var JSONobject = eval('(' + JSONtext + ')');

I was getting " ) Expected Error "

After that I deleted browser cache. Restarted the browser, now the code seems working very fine.

A: 

You should verify JSON format, look up there - http://ru.wikipedia.org/wiki/JSON

HWTech
I have changed this question as an example. Sorry, if I am violating the forum rules.
Vinothkumar Arputharaj