user3715910 user3715910 - 3 months ago 9
jQuery Question

parse json using ajax success function

I'm trying to display the json that i get and parse it in the success function of ajax.

What I have so far:

Ajax:

data = "Title=" + $("#Title").val() + "&geography=" + $("#geography").val();
alert(data);


url= "/portal/getResults.php";

$.ajax({
url: url,

type: "POST",
//pass the data
data: data,
dataType: 'json',

cache: false,
//success
success: function(data) {

alert(data);

}
});


getResults.php (JSON output):

{

"results": [
{
"DocId": 2204,
"Title": "Lorem ipsum dolor sit amet, consectetur",
"Locations": [
{
"State": "New York",
"City": ""
},
{
"State": "New York",
"City": "New York City"
}
],
"Topics": [
3,
7,
11
],
"PublicationYear": "2011",
"Organization": "New Yorks Times",
"WebLocation": "www.google.com",
"Description": "Lorem Ipsum"
}
],
"TotalMatches": 1

}


I expect the result in data to be the the json from getResults.php but instead I get [object Object].

I have also tried the code below but get no response:

success: function(data) {
var json1 = JSON.parse(data);
alert(json1);
}

Answer

since you're telling jQuery that you want dataType:'json', the ajax function parses the JSON response into an object for you. the result object you see should be an object with data matching the JSON response from your server. if you need the string version, try JSON.stringify(), otherwise you can just use the object as is: data['results'][0]['DocId'], etc

good luck!