JQuery AJAX request events - done, failed, success

I have a code like this

var ajaxrequest = $.ajax({ type: "POST", dataType: "json", url: "xy.php", data: { action : "read" } }).fail(function(){ //something to do when ajaxreq fails }).done(function(data){ //something to do when ajaxreq is done }); 

He does not work. My question is why this is not working:

 var ajaxrequest = $.ajax({ type: "POST", dataType: "json", url: "n3_vaje_api.php", //Relative or absolute path to response.php file data: { action : "read", }, fail:function(){ //something to do when ajaxreq fails }, done:function(data){ //something to do when ajaxreq is done } }); 

Failure and termination are just examples, they also don't work if they are used internally. But using it outside, like:

 ajaxrequest.complete(f(){}); 

works just fine ... I know, instead of doing, I have to use success, but that is not my point here. What is the deal here?

+5
source share
3 answers

you need to use success, and error is the method you need to use if you want to use your second option

this is an ajax request example without promises where you get success and error function as parameter

  $.ajax({url:"demo_test.txt" ,error : function (xhr,status,error) { //alert error} ,success:function(result){ $("#div1").html(result); }}); 

In the first sentence, you use the promise of the return by ajax requst object, which is the reason you make and refuse.

this is an example of a promised object, below an example of a request is a promise object

 var request = $.ajax({ url: "script.php", type: "POST", data: { id : menuId }, dataType: "html" }); request.done(function( msg ) { $( "#log" ).html( msg ); }); request.fail(function( jqXHR, textStatus ) { alert( "Request failed: " + textStatus ); }); 
+4
source

Withdrawal notification: jqXHR.success (), jqXHR.error (), and jqXHR.complete () callbacks are removed with jQuery 3.0. Instead, you can use jqXHR.done (), jqXHR.fail (), and jqXHR.always ().

0
source

You can simply use $ .post instead of $ .ajax and json as the fourth argument.

 $.post("n3_vaje_api.php", {action : "read"}, function(response) { // Do something with the request }, 'json') .done(function() { alert( "second success" ); }) .fail(function() { alert( "error" ); }) .always(function() { alert( "finished" ); }); 
-1
source

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


All Articles