8. December 2015
von Blackbam

Thats a very annoying common problem I discovered – if calling Ajax within a Javascript loop the callback function will be called asynchronously. That means: All local variables in the callback function will have their future value instead the value they had when the loop was running.

 

Example 1 (probably unwanted results):

var types = ["boring","stupid","funny"];

for(key in types) {
    var type=types[key];

    $.ajax({url: "/?connection=get&type="+type, success: function(result){
        $('#'+type).html(result);
    }
    });
}

Result: Only #funny is populated (with the results of the last callback, no matter which ends last).

 

Example 2 (solution):

var types = ["boring","stupid","funny"];

for(key in types) {
    var type=types[key];

    (function(type) {
        $.ajax({url: "/?connection=get&type="+type, success: function(result){
            $('#'+type).html(result);
        }
        });
    })(type);
}

Result: The elements with ids #boring, #stupid and #funny are populated with the result of the corresponding callback.

 

Explanation: You have created a closure which is preserving the value of type according to the current iteration.

Share

Warning: Undefined variable $time_since in /home/.sites/609/site1266/web/blackbams-blog/wp-content/themes/SilentWoodsByBlackbam/single.php on line 42 Dieser Eintrag wurde am 8. December 2015 um 19:19 in der Kategorie JavaScript / Ajax, jQuery, Web Development veröffentlicht. You can book the comments for this article RSS 2.0. Feedback, discussion, commendation and critics are welcome: Write a comment or trackback.


Tags: , , , ,

Fatal error: Uncaught Error: Undefined constant "Ext_related_links" in /home/.sites/609/site1266/web/blackbams-blog/wp-content/themes/SilentWoodsByBlackbam/single.php:75 Stack trace: #0 /home/.sites/609/site1266/web/blackbams-blog/wp-includes/template-loader.php(106): include() #1 /home/.sites/609/site1266/web/blackbams-blog/wp-blog-header.php(19): require_once('/home/.sites/60...') #2 /home/.sites/609/site1266/web/blackbams-blog/index.php(17): require('/home/.sites/60...') #3 {main} thrown in /home/.sites/609/site1266/web/blackbams-blog/wp-content/themes/SilentWoodsByBlackbam/single.php on line 75 internal_server_error <![CDATA[WordPress &rsaquo; Error]]> 500