views:

58

answers:

2

So, this should be simple in my mind... I have a valid JSON string being returned through an Ajax post:

{"success":true,"message":"Thank you! We value your feedback."}

And I'm simply trying to alert my "message" value onto my resulting post return:

success: function (result) {
   alert(result);
   var obj = $.parseJSON(result);
   alert(obj.message);
  },
error: function (req, status, error) {
   alert("Sorry! We could not receive your feedback at this time.");
  }

My "obj" attributes somehow aren't being recognized..... I've validated the JSON string to make sure it was valid, so what am I missing here?

+2  A: 

You shouldn't need to parse your JSON. Set the dataType attribute to json and jQuery will parse it for you. Then, result is essentially your JSON and you can do alert(data.message);.

jQuery.ajax({
  ...
  dataType: "json",
  success: function(data) {
     alert(data.message);
  },
  ...
});
Vivin Paliath
EXCELLENT! Thank you so much!
denisb
+1  A: 

What may be happening in this case is that jQuery is already treating your result as a JSON object. If your server returns the data with a MIME type of application/json, jQuery will detect that you're returning JSON and set the result to a javascript object rather than a string.

Ryan Brunner