Catch callbacks from an ajax

Asked

Viewed 4,206 times

2

For example:

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

Where does this function defined in done() go? I’ve searched the entire object using the console Chome, but I can’t find where are registered these callbacks ( console.log( teste ) )

If only I could shoot the "done’s" of the ajax like a teste.trigger("done") was good enough.

Someone can help me?

Thank you

  • 1

    Explain better what you mean by "stored". Do you mean jQuery? or your code? Can you also explain what you intend to do? You can always define the function separately function fnTeste(){} and then move on to ajax: var teste = $.ajax({...}).done(fnTeste); or call her directly fnTeste();.

  • I need to get the "registered" functions in the done() of an ajax

  • I still don’t understand what you really want.

3 answers

3

Come on,

Regardless of your problem, "catch" or "rotate" the done doesn’t make sense. I’ll explain why.

inserir a descrição da imagem aqui

How it works

The Done: is an internal jquery method that is executed after an ajax call is completed. The sequence roughly works like this:

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

And now because it doesn’t make sense

It doesn’t make sense precisely because you would need to pass the data returned from a request that is only present in the scope of the plugin itself. The Done method is precisely the reason for this.

1

Short answer: there is no native method.

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

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

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

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 on closures: How closures work in javascript?

  • How would I shoot the done of teste, following my example?

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 read process of 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 whole process on the server side, usually it is apache, but it can be an IIS...(I will not discuss it here!)

Inside the server there is another preconfigured layer that will handle your HTTP output, that is where the rules will be enabled, of how..., how long..., what limitations, permissions etc... to then send inside the document containing the PHP language, or the language being 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 the processing of this data, in the language, will enter the final request, which is from 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 on the Chrome console, log in to the Network > select the option XHR, and click on the file sent in your request, if it is not listed, make a request again so that it is listed, there have all the options you want to see about the behavior of the object and your request.

PS: Another thing that is important to know, is that a closures method with callback, will only have exit within itself, you can not use a callback outside its scope. What you can do is call an external method into that method, but still, it will run within it.

Another thing you can do is 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, what 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 jQuery’s own method for this:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.