-1
pfr = "";
      $.get("pfc.html", function (pfc) {

      from(pfc);
     });

     function from(pfc) {
         pfr = pfc;

          }
     ptr = "";
   $.get("pdate.html", function (ptc) {
          to(ptc);
        });
 function to(pc) {
        ptr = pc;

     }
                //alert(pfr);
                console.log(pfr);
                console.log(ptr);

The Problem is when i removed comments of alert(pfr) the console shows two empty strings , when i uncommented it, i am getting values of what i want. Actually These works fine with ajax calls too. The problem here is i want to make one more ajax call or get call but in that case everything is showing empty string.

I want the data from 3 ajax calls and save them as variables and access it globally for further use in script Any Ideas?

Thanks in advance

abdul riyaz
  • 80
  • 1
  • 1
  • 10
  • 1
    welcome to the world of asynchronous programming. It is like ordering delivery pizza, you can not eat it until it shows up at your door. – epascarello Jan 28 '16 at 19:08

1 Answers1

0

The reason for this is because the AJAX call you're making is asynchronous, meaning it doesn't run sequentially with the rest of your JavaScript, it runs at at the same time as it. When you use alert, your program has time to wait and those values end up being filled, but when you take out the alert you are printing out pfr before they have a value.

To solve this you can assign your ajax to a variable, like this:

 var ajax1 = $.get("pfc.html", function (pfc) {
     from(pfc);
 });
 //the variable ajax1 is referred to as a "Promise"

and put your console.log() wrapped in a $.when().then like this

$.when(ajax1).then(function() {
    console.log(pfc);
});

If you have multiple AJAX calls you need to make, just format the when like this:

$.when(ajax1, ajax2, ajax3).then(function() {
    console.log(pfc);
});

assuming that ajax1, ajax2, and ajax3 are all ajax calls.

Thomasov
  • 81
  • 4
  • `$.when` is not necessary unless you have multiple, and then you don't use `&&`, you separate them with `,`. – Kevin B Jan 28 '16 at 19:09
  • Thank you Thomasov I got what i want ,Actually i guessed the same that alert gives some time to process ajax but i dont know how to overcome that problem . Thanks alot, Now i got 3 values what i want with 3 ajax calls, I need to process them individually so i haven't used && – abdul riyaz Jan 28 '16 at 19:19
  • Kevin B, I fixed my error with when, thanks for pointing it out. I know that you can just use .then on a promise but I like the verbosity of putting it in a when. I guess it doesn't matter a ton. – Thomasov Jan 29 '16 at 14:31