0

I'm making an AJAX call to this php file:

<?php 
    $result = array('error' => "Please enter a valid name");
    echo  json_encode($result)
?>

In my javascript file, I have:

$.ajax({
    type:"POST",
    url:"/controller/common/review_processing.php", 
    data:dataString, 
    success:function (data) {
        var returned_data = data;
        console.log(returned_data); <---This outputs {"error":"Please enter a valid name"} 
        console.log(returned_data.error); <---This outputs undefined
    }

});

My data seems to be encoded as a JSON object correctly but when I try to access a specific property, I get an undefined result.

What I want is for console.log(returned_data.error) to output:

Please enter a valid name

What am I doing wrong?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Lars
  • 7,908
  • 11
  • 52
  • 70
  • possible duplicate of [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – Felix Kling Mar 15 '13 at 13:15
  • 1
    However, you can also provide the `dataType: 'json'` option to `$.ajax` and jQuery will parse the response automatically for you. – Felix Kling Mar 15 '13 at 13:16

2 Answers2

2

Please try :

$.ajax({
    type:"POST",
    url:"/controller/common/review_processing.php", 
    data:dataString,
    dataType: "json", <--response itself will be handled as JSON
    success:function (data) {
        var returned_data = data;
        console.log(returned_data); <---This outputs {"error":"Please enter a valid name"} 
        console.log(returned_data.error); 
    }

});
0

Try using this...

$.map(data.d, function (item) {
  console.log(item.error);
});
Prashant16
  • 1,514
  • 3
  • 18
  • 39