13

In my $.ajaxSucess() function I need to find out if the response is json. Currently I am doing this:

$('body').ajaxSuccess(function(evt, xhr, settings) {
    var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/);
    if(contType && contType.length == 2 && contType[1].toLowerCase() == 'application/json'){    
...

Is there a better way?

Ibrahim Tareq
  • 336
  • 2
  • 12
mkoryak
  • 57,086
  • 61
  • 201
  • 257

5 Answers5

26

Assuming that you are expecting json, I'd simply try and parse it like json and catch any errors. Also see jQuery.parseJSON.

try {
    jQuery.parseJSON(response);
} catch(error) {
    // its not json
}

If you are expecting one of a number of different response types (i.e. it might be json or it might just be text, etc) then you might need to get more complicated. I'd use xhr.getResponseHeader("content-type"). See this blog post for some great detail on handling content types.

$.ajax({
    type: "POST",
    url: "/widgets", 
    data: widgetForm.serialize(), 
    success: function(response, status, xhr){ 
        var ct = xhr.getResponseHeader("content-type") || "";

        if (ct.indexOf(‘html’) > -1) {
            widgetForm.replaceWith(response);
        }

        if (ct.indexOf(‘json’) > -1) {
            // handle json here
        } 
    }
});
jtfairbank
  • 2,311
  • 2
  • 21
  • 33
  • this is exactly what i wanted. somehow i missed the `getResponseHeader` method, this will save me from doing that messy regex – mkoryak Oct 05 '11 at 15:41
8

I have always found the following to work just fine:

  if (xhr.getResponseHeader('Content-Type') !== 'application/json') {
    // Something other than JSON was returned
  }

Did you run into a situation that required the extra logic in your post?

Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44
  • If you are certain that the server always returns the correct Content-Type header, and you just wish to see whether the response text is JSON, then this solution is better than using jQuery.parseJSON(), since it is less computationally intensive. If, however, you actually plan on doing anything with the response text, you will need to use jQuery.parseJSON(). – Richard Keller Apr 16 '14 at 11:16
  • 2
    Note that content type can contain encoding info as well. E.g. 'application/json; charset=utf-8'. See [What does "Content-type: application/json; charset=utf-8" really mean?](http://stackoverflow.com/questions/9254891/what-does-content-type-application-json-charset-utf-8-really-mean) – Stijn De Vos Sep 05 '14 at 08:36
1
var a={"k":"v"};
var b="k";

try{
 $.parseJSON(b);
}catch(e){alert('Not JSON')}
Muhammad Usman
  • 12,439
  • 6
  • 36
  • 59
0

If you are expecting the data form ajax response, you could handle it with following ajax call:

$.ajax({
  dataType: "json", //dataType is important
  type: 'post',
  url: orifinalurl,
  data: reqParam,
}).done(function(data){
    //response is valid json data.
}).error(function(jqxhr, exception){
    if (jqxhr.status === 0) {
        msg='Can not connect to server. Please check your network connection';
    } else if (jqxhr.status == 404) {
        msg='Requested page not found. <b>Error -404</b>';
    } else if (jqxhr.status == 500) {
        msg='Internal Server Error <b>Error -500</b>].';
    } else if (exception === 'parsererror') {
        msg='Requested JSON parse failed.';
    } else if (exception === 'timeout') {
        msg='Request Time out error.';
    } else if (exception === 'abort') {
        msg='Request aborted.';
    } else {
        msg='Uncaught Error.n' + jqxhr.responseText;
    }
});
0

You could probably use jQuery.parseJSON to attempt parsing it. If an exception is raised then it's not valid json.

http://api.jquery.com/jQuery.parseJSON/

Chris Pietschmann
  • 29,502
  • 35
  • 121
  • 166