JQuery ajax error callback not working

I am requesting an ajax url that results in a 500 HTTP header. I expect this to call the error function:

$.ajax({ url: "http://xxx", dataType: "jsonp", crossDomain: true, success: function( data ) { alert('success'); }, error: function () { alert('error'); } }); 

This works in safari, but does not work in chrome and firefox.

What am I doing wrong?

This is the latest jquery 1.4.X for reasons that I cannot upgrade to later versions.

The response sends an HTTP code of 500, an application like content / json, and content:

jsonp1310063232212 ({"error": {"reason": "User not found"}})

+6
source share
3 answers

It looks like crossDomain: not added before jQuery 1.5.

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

crossDomain (added 1.5)

Default: false for requests with one domain, for cross-domain requests.

If you want to force the crossDomain request (e.g. JSONP) in the same domain, set crossDomain to true. This allows, for example, server side redirection to another domain

Like Martin Larente in his comment, this could be a problem with how different browsers or jQuery detect / report JSONP errors.

+3
source

As stated in the JQuery documentation [1], an error handler is not called for cross-domain script and JSONP requests. It worked (not always) in older versions of jQuery.

I decide to use a compact and efficient plugin that includes a good error handler: http://code.google.com/p/jquery-jsonp/

Download it and add it to the head:

 <script src="javascripts/jquery.jsonp-2.2.0.min.js" type="text/javascript"></script> 

Then you can use the $ .jsonp () function similar to $ .ajax ():

 $.jsonp({ url: "http://xxx?callback=?", data: { var: 'test' }, cache: false, success: function(data, textStatus) { // ... }, error: function(xOptions, textStatus) { console.log('Error'); // ... } }); 

[1] http://api.jquery.com/jQuery.ajax/

+6
source

Unsolved problems seem to be visible with this. Cancel ajax JSONP request using jQuery

+2
source

Source: https://habr.com/ru/post/892256/


All Articles