Asked  6 Months ago    Answers:  5   Viewed   84 times

I have been working with jQuery and AJAX for a few weeks now and I saw two different ways to 'continue' the script once the call has been made: success: and .done.

From the synopsis from the jQuery documentation we get:

.done(): Description: Add handlers to be called when the Deferred object is resolved.

success: (.ajax() option): A function to be called if the request succeeds.

So, both do something after the AJAX call has been completed/resolved. Can I use one or the other randomly? What is the difference and when one is used instead of the other?

 Answers

36

success has been the traditional name of the success callback in jQuery, defined as an option in the ajax call. However, since the implementation of $.Deferreds and more sophisticated callbacks, done is the preferred way to implement success callbacks, as it can be called on any deferred.

For example, success:

$.ajax({
  url: '/',
  success: function(data) {}
});

For example, done:

$.ajax({url: '/'}).done(function(data) {});

The nice thing about done is that the return value of $.ajax is now a deferred promise that can be bound to anywhere else in your application. So let's say you want to make this ajax call from a few different places. Rather than passing in your success function as an option to the function that makes this ajax call, you can just have the function return $.ajax itself and bind your callbacks with done, fail, then, or whatever. Note that always is a callback that will run whether the request succeeds or fails. done will only be triggered on success.

For example:

function xhr_get(url) {

  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json',
    beforeSend: showLoadingImgFn
  })
  .always(function() {
    // remove loading image maybe
  })
  .fail(function() {
    // handle request failures
  });

}

xhr_get('/index').done(function(data) {
  // do stuff with index data
});

xhr_get('/id').done(function(data) {
  // do stuff with id data
});

An important benefit of this in terms of maintainability is that you've wrapped your ajax mechanism in an application-specific function. If you decide you need your $.ajax call to operate differently in the future, or you use a different ajax method, or you move away from jQuery, you only have to change the xhr_get definition (being sure to return a promise or at least a done method, in the case of the example above). All the other references throughout the app can remain the same.

There are many more (much cooler) things you can do with $.Deferred, one of which is to use pipe to trigger a failure on an error reported by the server, even when the $.ajax request itself succeeds. For example:

function xhr_get(url) {

  return $.ajax({
    url: url,
    type: 'get',
    dataType: 'json'
  })
  .pipe(function(data) {
    return data.responseCode != 200 ?
      $.Deferred().reject( data ) :
      data;
  })
  .fail(function(data) {
    if ( data.responseCode )
      console.log( data.responseCode );
  });
}

xhr_get('/index').done(function(data) {
  // will not run if json returned from ajax has responseCode other than 200
});

Read more about $.Deferred here: http://api.jquery.com/category/deferred-object/

NOTE: As of jQuery 1.8, pipe has been deprecated in favor of using then in exactly the same way.

Tuesday, June 1, 2021
 
conmen
answered 6 Months ago
60

You need to change the success callback to

response($.map(data, function(v,i){
    return {
                label: v.MainName,
                value: v.MainItemID
               };
}));

Fiddle.

The jQuery.map helps to Translate all items in an array or object to new array of items.

Update: Add Filter

$("#mainIngredientAutoComplete").autocomplete({
    source: function (request, response) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
        $.ajax({
            url: "../api/IngredientChoices",
            dataType: "json",
            success: function (data) {
                response($.map(data, function(v,i){
                    var text = v.MainName;
                    if ( text && ( !request.term || matcher.test(text) ) ) {
                        return {
                                label: v.MainName,
                                value: v.MainItemID
                               };
                    }
                }));
            }
        });
    }
});
Tuesday, August 10, 2021
 
stfn
answered 4 Months ago
19

$.ajaxSetup() - Set default values for future Ajax requests. You could, for example, set the ajax URL that you always want to use for every request here.

Example:

$.ajaxSetup({
  // Always use this URL for every request
  url: "http://example.com/ajax.php"
});

$.ajaxPrefilter() - Modify existing options before each request is sent. You could, for example, append a query string component to every ajax request that is sent out.

Example:

$.ajaxPrefilter( function(options) {
    // Always add "?debug=1" to every URL
    options.url += (options.url.indexOf("?") < 0 ? : "?" : "&") + "debug=1";
});
Tuesday, August 10, 2021
 
FreedomOfSpeech
answered 4 Months ago
85

Well there is no advantage of doing that in that particular situation.

The point of the .done() .fail() .always() methods is that you can

  1. Attach multiple handlers
  2. Do so anywhere and not just when calling $.ajax

If you are at the $.ajax call site only attaching single handlers then those advantages don't really come into play.

So you can return the promise and others may attach their own handlers.

Example is refreshing plugins after ajax request:

$.ajaxPrefilter(function(opt, origOpt, jqxhr) {
    jqxhr.always(function() {
        $("[data-plugin]").plugin();
    });
});
Saturday, September 4, 2021
 
Carrot
answered 3 Months ago
98

The buffer chunk sizes are applied in node. Nothing you do outside of node will solve the problem. There is no way to get what you want from node without a little extra work in your messaging protocol. Any message larger than the chunk size will be chunked. There are two ways you can handle this issue.

  1. If you know the total output size before you start to stream out of C, prepend the message length to the data so the node process knows how many chunks to pull before terminating the entire message.
  2. Determine a special character you can append to the message you are sending from the C program. When node sees that character, you end the input from that message.
Wednesday, October 20, 2021
 
Anton Barinov
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share