Kevin Burke
Kevin Burke

Reputation: 65004

How to handle a JSON request that doesn't return JSON?

In the good case my JSON endpoint will return a proper JSON response: {status: "success"}. However if my webserver 500 errors the 500 response body is HTML, which results in a SyntaxError if jQuery tries to parse it with $.parseJSON.

This question suggests just removing the dataType param from the request. I would rather not do that, is there a way to try/catch the SyntaxError thats raised by a non-JSON response?

Upvotes: 3

Views: 167

Answers (1)

Okan Kocyigit
Okan Kocyigit

Reputation: 13441

From jQuery API

Important: As of jQuery 1.4, if the JSON file contains a syntax error, 
the request will usually fail silently.

You can handle it the error callback.

$.ajax({
        url: "MYURL",
        dataType: 'json',
        success: function(data) {

        },
        error: function(e) {
          if(e.status == 500)
            alert("500 Internal Server Error");
        }
});

Upvotes: 1

Related Questions