tags:

views:

42

answers:

3

How can I determine the response type of ajax call in Jquery? At times, the server sends json response and at times it sends only the html for display purposes. Right now I am using

if(response.indexOf('Error)
  //popup error message
else
 response.username
 response.address
+2  A: 

You can try it like:

$.ajax({
  type: "POST",
  url: "your url goes here", 
  data: "data to be sent", 
  success: function(response, status, xhr){ 
    var ct = xhr.getResponseHeader("content-type") || "";
    if (ct.indexOf('html') > -1) {
      //do something
    }
    if (ct.indexOf('json') > -1) {
      // handle json here
    } 
  }
});

Basically it is also using indexOf but it seems more reliable.

anand
BTW I would suggest you to use only one format if possible. Like even if you are showing some simple message, you can use the json also.
anand
Thanks a lot. This is exactly what I am looking or.I wish jquery has a a shortcut for this :)
sam
A: 

Did you try looking at the header MIME type of the response?

Dick
A: 

To accept a JSON reply, you can set the reply type as JSON. I usually design my server side code so they always return JSON reply. In the event it fails to do so for whatever reason, I would get an error in my AJAX call for having incorrect JSON format and I can process the reply from server as not being non JSON.

error: function(response, status, xhr){ 
// do something with the reply.
}
Gunner