Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding jQuery's jqXHR

I have a set of $.get() requests that I need to refactor to include a failure callback. The requests are of the form

$.get(url,
      {},
      function(data) {//success, do work
      //work
      },'json');//or 'html'

According to the jQuery API, I simply add a jqHXR object. So in my case, I believe I should do

var jqxhr =  $.get(url,
          {},
          function(data) {//success, do work
          //work
          },'json').error(function() { alert("error"); });//or 'html'

I don't understand the reason for the second success callback in the example. I suppose it could be there for setting up a callback chain. I want error to execute in error, and success to execute on success. So, is this correct?

like image 652
P.Brian.Mackey Avatar asked Oct 03 '11 18:10

P.Brian.Mackey


3 Answers

I think the second success callback in the example is just there to illustrate that, using this syntax, you can have multiple handlers for success, error, and complete events. In the standard jQuery .ajax() method, you can only assign a single handler to each of these events. I can't think offhand of an example that would require multiple handlers, but it does seem a little clearer and more like the standard jQuery idiom to use

$.get('my_url.php')
    .success(handlerOne)
    .success(handlerTwo);

instead of

$.get('my_url.php', function(data, textStatus, jqXHR) {
    handlerOne(data, textStatus, jqXHR);
    handlerTwo(data, textStatus, jqXHR);
});

In your case, though, it might be easier and cleaner to just convert your $.get() statements to $.ajax(). The $.ajax() syntax is probably more familiar to most jQuery programmers, and since you don't need the special functionality (multiple handlers, post-request handler assignment) available in the other syntax, there's no reason not to just use $.ajax():

$.ajax({
    url: url,
    success: function(data) {
        // success, do work
    },
    error: function(data) {
        // error, handle failure
    },
    dataType:'json'
});
like image 110
nrabinowitz Avatar answered Sep 24 '22 13:09

nrabinowitz


This page has a lot of documentation on how jqXHR (jQuery XHR) differs from XHR (XMLHttpRequest).

http://api.jquery.com/jQuery.ajax/#jqXHR

like image 23
Steve Tauber Avatar answered Sep 22 '22 13:09

Steve Tauber


The code you are using should be fine. The second success is just another place where you can define a success method. Some people use the jqxhr success instead of the one passed into $.get(), and others use the deferred object's done handler to do the same.

like image 20
Kevin B Avatar answered Sep 24 '22 13:09

Kevin B