5
votes

I have tried almost everyway here on stack overflow, but somehow I cannot read JSON string data returned from a success function call in jquery ajax. my success function receives following JSON string:

Object {
  readyState = 4, responseText = "{"
  Response ":200,"
  Data ":"
  6 ","
  Message ":"
  6 "}", status = 200, statusText: "OK"
}

This is my success callback:

success: function(response, msg, responseText) {
   if (response.Response == 200) {
     console.log("Data was submitted");
     var obj = responseText;

     console.log(typeof obj);
   } else if (response.Response == 400) {
     console.log("there was some error");
   }
 }

When success function is fired and checks for status code, it executes console.log("Data was submitted"); statement successfully, however, I am not able to access the "Data":"6" key/value pair.

So far I have tried doing this:

var obj = responseText;
console.log(obj.Data);

and

console.log(obj.data[1]);

and numerous other ways, but either it says "undefined" or gives and error. However, when I console.log(obj), in console it shows 'obj'. which means I am getting a JSON object.

Please note that I have also tried:

obj = jQuery.parseJSON(responseText);

which gives me an error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

What to do in this situation? I want to be able to extract the value of a key name "Data": and and assign its value ="6" to a variable.

2
response.Response, response.Data and response.Message - Rory McCrossan
Hi @RoryMcCrossan Thank you for your response. I tried doing this as you suggested: obj = responseText; console.log(obj.Data); However, it suggests: undefined - Zafar
Hi @RoryMcCrossan Oh Oh Oh! IT WORKED. Thank you man. Such a simple mistake. Please post it as an answer. So that I can mark it. - Zafar
response.Response is returning the correct value. In the JSON object you provided Response and Data are part of the same object... Have you tried response.Data instead of responseText.Data - Antonio Manente
@Zafar Darin got the same answer. The issue is that you're accessing the wrong parameter of the success handler - Rory McCrossan

2 Answers

4
votes

The first parameter of the success callback is what you need, not the third. The first parameter will represent the body of the response as returned from the server. Also you don't need to be checking for anything different than 200 status code in a success callback. That's what the error callback is designed for because the success callback will never be fired if your server returns 400 status code.

So:

dataType: 'json',
success: function (response) {
    console.log("Data was submitted");
    console.log(response.Data);
},
error: function() {
    console.log("there was some error");
}
1
votes

The success callback is success: function(data, textStatus, jqXHR )

So the 1st, data will contain the data returned to the success function.