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
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: $.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With