Note that there are some explanatory texts on larger screens.

plurals
  1. POVariable overwritten when using asynchronous AJAX (using jQuery) request to load data
    primarykey
    data
    text
    <p>I have the following code that loads information about a users payments a month in advance of when it's needed. The function works when I wait for each month to load however it fails when multiple ajax requests are being run. Basically duplicate data gets added to my monthData array which implies that loadedPaymentMonth is being overwritten each function call. I'd like to load the data asynchronously so any thoughts?</p> <p>This doesn't work:</p> <pre><code>var monthData=[]; function loadMonth(monthToLoad,curMonth){ $("#paymentContent").find(".loader").remove(); var monthToGet; switch(monthToLoad){ case "Next": monthToGet=monthData.length-curMonth+1; break; case "Prev": monthToGet=-curMonth-1; break; case "This": monthToGet=currentMonthPointer-curMonth; break; } var loadedPaymentMonth=new PaymentMonth(); if(monthToGet&lt;0){ currentMonthPointer+=1; monthData.unshift(loadedPaymentMonth); } else{ monthData.push(loadedPaymentMonth); } $.getJSON(host+"GetDataForMonth.aspx?StartMonth="+monthToGet,function(data){ loadedPaymentMonth.setMonthData(data.monthData,data.month,data.year); if($("#paymentsContent").find(".loader").remove().length&gt;0){ loadedPaymentMonth.createPaymentRowsForMonth(); } }).error(function(){ $("#paymentsContent").find(".loader").remove(); }); } </code></pre> <p>This does:</p> <pre><code>function loadMonth(monthToLoad,curMonth){ $("#paymentContent").find(".loader").remove(); var monthToGet; switch(monthToLoad){ case "Next": monthToGet=monthData.length-curMonth+1; break; case "Prev": monthToGet=-curMonth-1; break; case "This": monthToGet=currentMonthPointer-curMonth; break; } var loadedPaymentMonth=new PaymentMonth(); if(monthToGet&lt;0){ currentMonthPointer+=1; monthData.unshift(loadedPaymentMonth); } else{ monthData.push(loadedPaymentMonth); } $.ajax({ url:host+"GetDataForMonth.aspx?StartMonth="+monthToGet, async:false, dataType:"json", success:function(data){ loadedPaymentMonth.setMonthData(data.monthData,data.month,data.year); if($("#paymentsContent").find(".loader").remove().length&gt;0){ loadedPaymentMonth.createPaymentRowsForMonth(); } } }).error(function(){ $("#paymentsContent").find(".loader").remove(); }); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload