Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous GET request with Javascript/jQuery

I have a function that makes ajax GET request and based on the value returned sets one global JS variable. I use this variable (isCalculateTax in the code below) for further processing:

var isCalculateTax;

function setCalculateTaxValue(taxStatementId) {
 $.get('/taxstatements/calculatetax/' + taxStatementId, function (data) {
  isCalculateTax = data.isCalculateTax;
 });
}

$(document).ready(function () {
 // initially check the tax statements dropdown to see which one is selected
 // and set the isCalculateTax to the right value
 var taxStatementId = $('#taxStatements').val();
 setCalculateTaxValue(taxStatementId);
 enumerateDocumentItems(isCalculateTax);
});

My problem is that when enumerateDocumentItems() is called and executed the isCalculateTax is not yet updated from the AJAX GET request, so I receive unpredictable results.

How can I wait the necessary amount of time before executing enumerateDocumentItems() so that isCalculateTax will be correct?

like image 788
mare Avatar asked Sep 27 '10 17:09

mare


1 Answers

There are two ways to do this. First, you could change setCalculateTaxValue (and probably rename it) so that it accepts a callback that gets executed when the value is retrieved. You'd then pass enumerateDocumentItems as the callback. Alternately, and this is really going against the concept of asynchronicity, you can change it to use $.ajax and set the aSync option to false. I recommend the former.

var isCalculateTax; // no longer needed?

function updateTaxValue(taxStatementId,callback) { 
 $.get('/taxstatements/calculatetax/' + taxStatementId, function (data) {
  isCalculateTax = data.isCalculateTax;
  if (callback) {
      callback.call( taxStatementId, data.isCalculateTax ); 
  }
 }); 
} 

$(document).ready(function () { 
 // initially check the tax statements dropdown to see which one is selected 
 // and set the isCalculateTax to the right value 
 var taxStatementId = $('#taxStatements').val(); 
 updateTaxValue(taxStatementId,enumerateDocumentItems); 
});

Using the callback makes it a little more flexible than simply referencing the callback function directly. It will allow you to reuse the update code for more than one purpose if necessary.

like image 106
tvanfosson Avatar answered Oct 07 '22 18:10

tvanfosson