sam
sam

Reputation: 773

jquery how to check response type for ajax call

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

Upvotes: 77

Views: 83316

Answers (5)

tyrion
tyrion

Reputation: 2303

If the response is parsed as JSON, the jqXHR object will have a responseJSON property.

$.ajax(
    // ...
).done(function(data, textStatus, jqXHR) {
    if (jqXHR.responseJSON) {
        // handle JSON
    } else {
        // handle html
    }
}).fail(function(jqXHR, textStatus, errorThrown) {
    if (jqXHR.responseJSON) {
        // handle JSON
    else {
        // handle html
    }
})

From the jQuery.ajax documentation:

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

Upvotes: 13

Imdad
Imdad

Reputation: 6032

You can simply use javascript's easy method to check the type

i.e.

if(typeof response=="object")
{
 // Response is javascript object
}
else
{
 // Response is HTML
}

If you use this method you don't have to write 2 extra parameter in the success callback.

Upvotes: 17

SolidALb
SolidALb

Reputation: 130

The answers above didnt work for me so I came up with this solution:

success: function(data, textStatus , xhr) {
if(xhr.responseXML.contentType == "text/html") {
    //do something with html
    }
else if(xhr.responseXML.contentType == "application/json") {
    //do something with json
    }}

Upvotes: 8

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

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.
}

Upvotes: 0

Ankit Jaiswal
Ankit Jaiswal

Reputation: 23427

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.

Upvotes: 138

Related Questions