Home » Jquery » javascript – jQuery ajax errors out if file not exists, even though error handler is set

javascript – jQuery ajax errors out if file not exists, even though error handler is set

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have the following code in my javascript:

ajaxCall() {
 return new Promise(function(resolve, reject) {
   jQuery.ajax({
      async: true
      data: { 
         ajaxCallid: "e4f7b812-579b-a347-11f7-ce660ce79b72", 
         javascript: true 
      },
      dataType: "jsonp",
      timeout: 10000,
      type: "GET",
      url: "https://my.site.url.com/my.json"
      xhrFields: { 
         withCredentials: true 
      }
   }).done(function(data) {
      // ...process the data...
      resolve(data);
   }).fail(function(jqXHR, textStatus) {
     // ... process errors...
     // test the nature of the error, and build an error = {} object
     resolve(error);
   });
 };
}

What I am expecting, is that, if I call the following function, and the https://my.site.url.com/my.json file does not exist, the fail callback of the jquery ajax should be ran, and my Promise should resolve to an error object built by the fail callback.

Instead of this, the fail callback fires, the error object is built and returned, but I also get an error in my console, sent by jQuery, that looks something like this:

SyntaxError: expected expression, got ‘<‘
  jQuery 6
    DOMEval
    globalEval
    text script
    ajaxConvert
    done
    callback

It seems to me, that altough an error is fired, jQuery tries to parse the result sent by the server, as a JSON result (which it is not, in the case the file does not exist, apache is throwing a html error message in this case).

If I am correct regarding on the nature of this error, is there any way to tell jQuery, to not try to parse the result as a json, in case any kind of error is being raised, and the fail callback is being fired?

I am using jquery 3.4.1.

How to&Answer:

You can look at status code 404 and run resolve to error.

You can also use fetch API

fetch('https://stackoverflow.com/some.json')
.then(function (data) {
    console.log('Request succeeded with JSON response', data);
  })
  .catch(function (error) {
    console.log('Request failed', error);
  });