0

Yes, this is another one of those "accessing a json with javascript". Indulge me, I read the rest of the answers, event this one, and didn't help.

I have the following code

var display_order_message = function(res, status) {
    alert(res.status+' '+res.message+' '+res["message"]);
};


$("#ticketform").submit( function(event) {
  data = {};
  var args = {
    type:"POST",
    url:"someurldoesntmatterhere",
    data:data,
    dataType:"json",
    success: somefunctionsheredontmattereither,
    complete: display_order_message
  };
  $.ajax(args);
  event.preventDefault();
});

Now, using Firebug I can see that the json which is returned is

{"status": 200, "qa": [], "message": "order canceled", "qb": []}

The alert in the code above prints

200 undefined undefined

So, why is it that I can access .status but not .message or ["message"]? And how to I access the message?

2 Answers 2

4

Put display_order_message in success arg instead of complete.

Currently, your res variable is a jqXHR which also has a status child.

See http://api.jquery.com/jquery.ajax/

Sign up to request clarification or add additional context in comments.

2 Comments

Yup, that was it. So I have to include display_order_message in both success AND error? Or better, what if I get a 400 which replies a json which also has an error message which I want to display? What do I do then?
You should have one callback function for each. They don't have the same parameters. You should use success callback to handle your data and your application layer error (res.status in your case). The error callback should be used to handle a jQuery layer (or lower) error.
-1

very simple

var obj = {"status": 200, "qa": [], "message": "order canceled", "qb": []}
var message = obj.message;
var message2 = obj['message'];

both works

3 Comments

Expand please? If var message = obj.message; works, why doesn't alert(obj.message);?
sorry i forgot this var result = eval('(' + res + ')');
eval is what you use if you are catering for ancient browsers. If you use a modern browser you use JSON.parse. If you are using jQuery (as is the case here), then you let jQuery do it for you! As pointed out in the Smoky's answer, res isn't a string of response data anyway, so this wouldn't work.

Your Answer

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