0

Basically I need a way to wait for the ajax call in the uniqueID() function to finish before it returns a value to the while call in the createColumns() function. Currently everything works fine however in HTML the id is undefined and about half a second after the functions are complete the id's that should be in the html are alerted.

The difference between my question and the one that was marked duplicate is that my call is in a while loop. Which means a callback function in success is not possible.

Please let me know if this doesn't make much sense. Thanks!

var uniqueid = ""; 
function uniqueID() {
  uniqueid = "";
  $.ajax({
    url: '....',
    type: 'post',
    data: { "uniqueidfunc": "1"},
    success: function(response) { 
      uniqueid = response; 
      alert(uniqueid);
      return uniqueid;
    }
  });
}

var i = "";
var columns = "";
function createColumns(x) {
  i = 0;
  columns = "";
  while (i < x) {
    columns += '<div class="column col-'+x+'" id="'+uniqueID()+'"></div>';
  i++;
  };
  return columns; 
}

$(document).delegate('.tcolumn', 'click', function(){
 colummnum = $(this).attr("id");
 colummnum = colummnum.replace("tcolumn-", "");
 $(this).parent().next().html(createColumns(colummnum));
});
Xirlas
  • 117
  • 1
  • 1
  • 11
  • What is the purpose of using a `while` loop ? What is expected result of `uniqueID()` ? – guest271314 Feb 20 '16 at 05:41
  • Am I being blind? Where do you call createColumns() in the first place? – amflare Feb 20 '16 at 05:41
  • @guest271314 The while loop creates the number of divs as per the number of columns clicked. – Xirlas Feb 20 '16 at 05:46
  • @amflare I've edited the function call in thanks. – Xirlas Feb 20 '16 at 05:46
  • @Xirlas You should be able to achieve requirement using single `.then()` following `$.ajax()` call – guest271314 Feb 20 '16 at 05:50
  • @guest271314 Like this: $.ajax().then({ ? That didn't work for me. – Xirlas Feb 20 '16 at 06:10
  • @Xirlas The `while` loop does not appear necessary. You can update `html` within `success` function or `$.ajax().then(function(response) { colummnum = $(event.target).attr("id"); colummnum = colummnum.replace("tcolumn-", ""); $(this).parent().next().html("
    ");})`
    – guest271314 Feb 20 '16 at 06:41

0 Answers0