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?

Community
  • 1
  • 1

2 Answers2

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/

Ludovic Guillaume
  • 3,237
  • 1
  • 24
  • 41
  • 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? –  Jan 05 '14 at 21:24
  • 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. – Ludovic Guillaume Jan 05 '14 at 21:38
-1

very simple

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

both works

gogagubi
  • 965
  • 1
  • 15
  • 36
  • Expand please? If var message = obj.message; works, why doesn't alert(obj.message);? –  Jan 05 '14 at 21:13
  • sorry i forgot this var result = eval('(' + res + ')'); – gogagubi Jan 05 '14 at 21:17
  • 2
    `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. – Quentin Jan 05 '14 at 21:18