Jquery ajax not ending

I am having problems with ajax requests and server responses:

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

The fact is that sometimes I get success when I need it, but sometimes I can get the status of 500, and this is normal and expected. The same ajax call works for correct requests, but is not suitable for others. I want to show an error message if I get a 500 server error, but for some reason ajax does not exit. Thus, neither error: nor complete: work. Maybe the reason for this is the jsonp data type? However, other data types do not work. Can anyone help?

Or maybe give me advice on how to determine server status in any other way.

+4
source share
4 answers

Jsonp requests do not cause design error callbacks , so you will not be able to catch the error with javascript. I suggest instead that you implement an error handler on your server that detects a jsonp request and returns jsonp, which indicates an error, not a 500 status code.

+3
source

Note that error: deprecated since 1.8 and is not called for JSONP, however I wonder if you can succeed using the Promise functionality introduced from 1.5 for deferred http://api.jquery.com/category/deferred- object / like:

 jqXHR.fail(function(jqXHR, textStatus, errorThrown) {}); jqXHR.done(function(data, textStatus, jqXHR) {}); jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { }); 

An example for your code:

 $.ajax({ url: servurl, dataType: "jsonp", data: {... }, crossDomain: true }).done(function(data, textStatus, jqXHR){ //replace success alert(textStatus); }).always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { // replace complete alert(textStatus); }).fail(function(jqXHR, textStatus, errorThrown) { // replace error alert(errorThrown); }); 
+1
source

Make sure you are accessing your server. Perhaps you are requesting a specific contentType on your server (e.g. application/json ) and you are not using this property in your ajax call.

As you requested, in order to show some message, if you get an error (400, 404, 500 ...), you can use my custom function to answer the ajax error:

 function onErrorFunc(jqXHR, status, errorText) { alert('Status code: ' + jqXHR.status + '\nStatus text: ' + status + '\nError thrown: ' + errorText); } 

Using:

 $.ajax({ //some options error: onErrorFunc }); 

Please show us what error started your server.

0
source

Thanks everyone for the comments. JQuery.ajax really does not give errors in jsonp requests. The way to get error messages was to implement the jquery-jsonp plugin: https://github.com/jaubourg/jquery-jsonp

0
source

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


All Articles