Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery how to read this JSON string from responseText

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.

like image 278
Zafar Avatar asked Dec 23 '15 15:12

Zafar


1 Answers

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");
}
like image 91
Darin Dimitrov Avatar answered Sep 30 '22 06:09

Darin Dimitrov