1

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 Answers 2

6

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);
  },
  ...
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.