0

I created a array outside the loop and added its value inside the loop, than i cant print use it outside the loop. here is my code , help me .

 

$(document).ready(function() {
    var usr_id = $("#user_id").val();
    var tabs_name = new Array("full_body", "hand_uper_limb", "lower_trunk" , "spine" , "upper_trunk") ; 
    var tab_order = new Array();    
    $.each(tabs_name , function(value) {    
        $.ajax({
            method: "POST",
            url: "kv_load.php", 
            data: { id: usr_id,  tbl_name : 'kv_'+tabs_name[value]},
            success: function(response) {              
                if(response == null || response =="" ) { } else {               
                    var obj = jQuery.parseJSON(response);
                    ax = jQuery.parseJSON(obj.x_coordinate);                    
                    if (ax!==null && ax.length!== 0) {
                        var len_x =ax.length; 
                    } else {
                        len_x =  0 ; 
                    }               
                    tab_order.push({    table: tabs_name[value],  size:  len_x });
                }                       
            },
            failure: function() {
                alert('failed to save your datas. ');
            }
        });         
    }); 
    $.each(tab_order, function (index, value) {
        alert( value.table + ' : ' + value.size );
    });
});

Here "tab_order" is my array variable, i declared it from the beginning of dom ready, And add items inside the each function, after that i come out to print the array, But it results empty. If you are not clear ,tell me I will explain in detail.

Thanks for all of your answers, Finally my problem is resolved here. with below answers,

  • because ajax is `Asynchronous` you can set `async : false` – Adil Shaikh Mar 26 '14 at 07:17
  • Thank you, It worked . Can i have your contact social id, fb, twitter, or skype.? –  Mar 26 '14 at 07:20
  • @MohammadAdil - eeeck. Don't set `async: false`. That is a very bad practice because it locks up the browser during the ajax call. The proper answer is to use proper asynchronous programming. See [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) for more explanation. – jfriend00 Mar 26 '14 at 07:23

2 Answers2

0

With asynchronous responses (which is what you get with Ajax calls), you have to do all processing of response data in the completion handler for the ajax call. If you want to wait until all ajax calls are done before processing all the results, then you have to check in each completion handler if this is the last one and, if so, then do your processing of the data. That way, regardless of the timing of the ajax responses, you will know that they are all now done.

Please do not use async: false with your Ajax calls. That will lock up the browser (it doesn't process any events or run any javascript) while the ajax call is running. It will not be a good user experience and even worse on slow networks or if the server is slow to respond. Proper asynchronous programming does not require setting async: false.

Here's one way to solve the problem by checking in each Ajax completion function if all the results have been collected now (e.g. the last Ajax call has completed). If so, then process the results. Here's how that code would look:

$(document).ready(function() {
    var usr_id = $("#user_id").val();
    var tabs_name = new Array("full_body", "hand_uper_limb", "lower_trunk" , "spine" , "upper_trunk") ; 
    var tab_order = new Array();    
    $.each(tabs_name , function(value) {    
        $.ajax({
            method: "POST",
            url: "kv_load.php", 
            data: { id: usr_id,  tbl_name : 'kv_'+tabs_name[value]},
            success: function(response) {              
                if(response == null || response =="" ) { } else {               
                    var obj = jQuery.parseJSON(response);
                    ax = jQuery.parseJSON(obj.x_coordinate);                    
                    if (ax!==null && ax.length!== 0) {
                        var len_x =ax.length; 
                    } else {
                        len_x =  0 ; 
                    }               
                    tab_order.push({    table: tabs_name[value],  size:  len_x });
                    // if all responses have now been received, 
                    // the results are all here and can now be processed
                    if (tab_order.length === tabs_name.length) {
                        $.each(tab_order, function (index, value) {
                            alert( value.table + ' : ' + value.size );
                        });
                    }
                }                       
            },
            failure: function() {
                alert('failed to save your datas. ');
            }
        });         
    }); 
});

Alternatively, one can use the deferred/promises capabilities in jQuery to help us get notified when multiple asynchronous operations have completed like this:

$(document).ready(function() {
    var usr_id = $("#user_id").val();
    var tabs_name = new Array("full_body", "hand_uper_limb", "lower_trunk" , "spine" , "upper_trunk") ; 
    var tab_order = new Array();    
    var promises = [];
    $.each(tabs_name , function(value) {    
        var jqXHR = $.ajax({
            method: "POST",
            url: "kv_load.php", 
            data: { id: usr_id,  tbl_name : 'kv_'+tabs_name[value]},
            success: function(response) {              
                if(response == null || response =="" ) { } else {               
                    var obj = jQuery.parseJSON(response);
                    ax = jQuery.parseJSON(obj.x_coordinate);                    
                    if (ax!==null && ax.length!== 0) {
                        var len_x =ax.length; 
                    } else {
                        len_x =  0 ; 
                    }               
                    tab_order.push({    table: tabs_name[value],  size:  len_x });
                }                       
            },
            failure: function() {
                alert('failed to save your datas. ');
            }
        });
        promises.push(jqXHR);
    }); 
    $.when.apply($, promises).done(function() {
        $.each(tab_order, function (index, value) {
            alert( value.table + ' : ' + value.size );
        });
    });
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

please try to it for resolving

$(document).ready(function() {
  var usr_id = $("#user_id").val();
  var tabs_name = new Array("full_body", "hand_uper_limb", "lower_trunk" , "spine" , "upper_trunk") ; 
  var tab_order = new Array();   
  $.each(tabs_name , function(value) {    
    $.ajax({
      method: "POST",
      url: "kv_load.php", 
      data: { id: usr_id,  tbl_name : 'kv_'+tabs_name[value]},
      success: function(response) {              
        if(response == null || response =="" ) { } else {               
          var obj = jQuery.parseJSON(response);
          ax = jQuery.parseJSON(obj.x_coordinate);                    
          if (ax!==null && ax.length!== 0) {
            var len_x =ax.length; 
          } else {
            len_x =  0 ; 
          }               
          tab_order.push({    table: tabs_name[value],  size:  len_x });
          // if all responses have now been received, 
          // the results are all here and can now be processed
          if (tab_order.length === tabs_name.length) {
            var deferred = $.Deferred();
            $.each(tab_order, function (index, value) {
              alert( value.table + ' : ' + value.size );
            });
            deferred.resolve();
            deferred.promise().done(function(){tab_order=[]});
          }
        }                       
      },
      failure: function() {
        alert('failed to save your datas. ');
      }
    });         
  }); 
});

please have a look on image also.

enter image description here

uma
  • 2,932
  • 26
  • 20