Catching callbacks from an ajax

2

For example:

var teste = $.ajax({...}).done( function() { alert('Callback Done!') } );

Where does this function defined in done () go? I already looked in the integer object using the Chome console, but I did not find where these callbacks ( console.log( teste ) ) are registered

If I could at least fire the "done's" of ajax as if it were a teste.trigger("done") , it was good.

Can anyone help me?

Thank you

    
asked by anonymous 15.11.2015 / 01:29

3 answers

3

Come on,

Regardless of your problem, "get" or "run" done does not make sense. I'll explain why.

How it works

Done: is an internal jquery method that runs after the ajax call completes. The sequence roughly works like this:

  • 1- Call is made ($ .ajax)
  • 2- The return is processed
  • 3- With return in hand jquery runs done indicating that it does not errors have occurred. This Done receives the data from the request.

And now because it does not make sense

It does not make sense just because you would need to pass the data returned from a request that is only present in the scope of the plugin itself. Just to expose such a data exists the Done method.

    
16.11.2015 / 17:09
1

First understand that there are different concepts about HTTP request.

When it comes to a Client / Server request, the URL that is sent via POST, GET, PUT or DELETE, made through an AJAX request, is sent directly to the Server, and the process of reading the file that will be waiting for this request will only receive the data, after identifying the protocol of your request and going through the process on the server side, usually is apache, but it may be an IIS ... (I will not discuss this here!)

Inside the server there is another preconfigured layer that will handle your HTTP output, that's where the rules will be enabled, how, how long, what limitations, permissions, etc. to send it to the document where it contains the PHP language, or the language that will be used for this dynamic.

And this file, will read and identify calls through language variables, in PHP we have:

  • $chamada = $_REQUEST['chamada'];
  • $chamada = $_POST['chamada'];
  • $chamada = $_REQUEST['chamada'];
  • $chamada = fopen("php://input", "r");
  • etc

After processing this data, in the language, the final request will be entered, which is the browser itself, and this will receive other reading data, which usually stay in the header of its scope, there it will identify information from the browser :

GET / HTTP/1.1
Host: spesa.com.br
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US) Gecko/20061201 Firefox/2.0.0.3 (Ubuntu-feisty)
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive

To access this information in Resful in the Chrome console, go to the Network > select the XHR option, and click on the file sent in your request, if it is not listed, make a request again to be listed, there are all the options you want to see about the behavior of the object and its requisition.

PS: Another thing that is important to know is that a closures method with callback will only have output inside itself, you can not use a callback out of its scope. What you can do is call an external method into that method, but still, it will execute inside of it.

Another thing you can do is to define an external variable outside of your callback method, assign it a return after changing the return of a callback, and then return that variable, which we call "promise." Example:

   var methodAction = function() {


        var promise = $.ajax({
              url: "/action.php",
              method: "POST",
              dataType:"json"
         });
            promise.when(whenFunction);
            promise.done(successFunction);
            promise.fail(errorFunction);
            promise.always(alwaysFunction);

     }


var successFunction = function(data) {
      return data;
}
var errorFunction = function(data) {
     $('#loading').text('erro no processo!');
}
var alwaysFunction = function(data) {
     $('#loading').text('processado!')
}
var whenFunction = function(data) {
     $('#loading').text('processando...')
}

methodAction();

There is a method of jQuery itself, for this:

$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  alert( jqXHR.status ); // Alerts 200
});

Deferred Object - Deferred object (extended)
Documentation
Read more here
More useful reading

    
16.11.2015 / 18:56
1

Short answer: There is no native method.

The jQuery.ajax() function returns an object that implements the Promise interface, which only allows the assignment of callbacks .

This interface is associated with a Deferred Object , this object encapsulates in a closure list of functions you want to access, and there is no method to access this list.

On firing callbacks , the function that would do this is deferred.resolve() , but this function is also encapsulated and can not be accessed directly.

The best alternative is to use named functions, as suggested by @Sergio in the comments:

function fnTeste() { // cria função nomeada
  alert('Callback Done!')
}
var teste = $.ajax({...}).done(fnTeste); // adiciona como callback
fnTeste(); // para disparar callback "manualmente"

Recommended reading about closures : How do closures work in javascript?

    
16.11.2015 / 18:21