I'm trying to get some javascript to run a for loop which will create an xml file and then, after the loop is complete, to visit a link that would allow the user to download the file. Currently what happens is that it gets half-way through creating the file and then sends the user the link to download the file.
I followed this question's advice and created a callback variable and moved the download link to another function, however that hasn't solved the problem either. Does anyone else have any idea how to do it? My code is:
var callbackcount=0;
function populateTemplate(numResults) {
  for (i=1; i < numResults; i++) {
    $.post('linkToTheFileThatCreatesTheXMLFile', {WithSomeParameters};
    download(numResults);
  }
}
function download(numResults) {
  callbackcount++;
  if (callbackcount == numResults) {
    window.location.href="linkToPHPThatDownloadsFile";
  }
}
Thanks heaps
Edit: Console.log results:
LOG: 230 LOG: 330 LOG: 230 LOG: 330 
LOG: 430 LOG: 530 LOG: 630 LOG: 730 
LOG: 830 LOG: 930 LOG: 1030 LOG: 1130 
LOG: 1230 LOG: 1330 
If numResults = 7
LOG: 27 LOG: 37 LOG: 47 
or
LOG: 27 LOG: 37 LOG: 47 LOG: 57 
etc.
Edit: The new code:
function populateTemplate(numResults) {
  var callbackcount = 1;
  for (i=1; i < numResults; i++) {
    $.post('linkToTheFileThatCreatesTheXMLFile', {WithSomeParameters}, function() {
      callbackcount++;
      console.log(callbackcount, numResults);
      if(callbackcount === numResults - 1) {
        window.location.href="linkToPHPThatDownloadsFile";
      }
    });
  }
}
 
     
     
    