Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery how to check response type for ajax call

Tags:

jquery

ajax

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 
like image 373
sam Avatar asked Sep 18 '10 11:09

sam


People also ask

How do I know if AJAX response is JSON?

If the response is JSON, a properly behaving application would set the Content-Type to application/json. So all you have to do, if the server is well-behaving, is to test if the Content-Type header in the response starts with application/json. By chance, jQuery already does this by itself: $.

What is response type in AJAX?

Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties.

What is dataType in AJAX call?

The dataType option specifies the type of response data, in this case it is JSON. The timeout parameter specifies request timeout in milliseconds. We have also specified callback functions for error and success. The ajax() method returns an object of jQuery XMLHttpRequest.


1 Answers

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.

like image 162
Ankit Jaiswal Avatar answered Dec 09 '22 23:12

Ankit Jaiswal