views:

3942

answers:

2

Ok, I'm a bit new when it comes to jQuery and json. If I'm using json as my return type, can I still retrieve responseText from an XMLHttpRequest object?

here's the code that i'm using:

json response: {"clients": []}

$.ajax({
        type: "POST",
        url: "/myurl/whatever.php",
        data: myData,
        dataType: "json",

     success: function(msg){
      status.html(msg[0]);
        },
     error: function(msg) {
             status.html("Error: " + msg[0]);
     }

        });

is the use of msg[0] correct if i want to output the json response or am i missing something?

how can i still use the above code with XMLHttpRequest to get the status, responseText, etc.

thanks, all!

+1  A: 

If you're using json, then you get a json object back, not an XML object. You can output it directly, without using [0].

cloudhead
what about the response codes; 200, 500, etc. or would that also come back with the XML object?
I'm not sure you can access the status from within the callback, in case of a json object, but what you can do is have your server side script add the status to the json object before sending it, just like any other field. Then you can check it through json.status.
cloudhead
A: 

As far as I know, the call to $.ajax returns a XHR object, and from that the responseText can be extracted, e.g.:

var xhr = $.ajax( {
                        url:' someInfo.php',
                        data: 'which=squirrels',
                        asynch: true
                } );

var resp = xhr.responseText;

The response text will contain a json string, which would need to be converted to an object to be of any use.

If you want to use the response as a json object directly within your success: function, do as @cloudhead suggested, and use msg. The dataType : "json" in your options takes care of the conversion for you.

karim79