Search code examples
javascriptjqueryprototypejs

What is jQuery's equivalent to Ajax.Request, along with onSuccess and onComplete?


Here's my code:

this.ajax = new Ajax.Request(this.url, {
  method: 'get',
  parameters: { 'timestamp' : this.timestamp },
  onSuccess: function(transport) {
    // handle the server response
    var response = transport.responseText.evalJSON();
    this.comet.timestamp = response['timestamp'];
    this.comet.handleResponse(response);
    this.comet.noerror = true;
  },
  onComplete: function(transport) {
    // send a new ajax request when this request is finished
    if (!this.comet.noerror)
      // if a connection problem occurs, try to reconnect each 5 seconds
      setTimeout(function(){ comet.connect() }, 5000); 
    else
      this.comet.connect();
    this.comet.noerror = false;
  }
});

I mainly want to know about the onComplete function, that's what I'm pondering over.


Solution

  • One such function is .ajax. The documentation is quite exhaustive: jQuery .ajax function.

    An example of onSuccess and onComplete-like functionality might be something like this...

    $.ajax({
        url: "test.php",
        type: "post",
        data: values,
        success: function() {
            alert("success");
        },
        error: function() {
            alert("failure");
        },
        complete: function() {
            alert("both success and error have been checked, request finished!");
        }
    });
    

    There are also individual .post and .get functions, but they are best avoided as they make assumptions about the response, and that can lead to unintended failures.