0

I have some javascript code that makes an ajax call, get's a var and then attempts to use the var later in the script. The problem is because of the ajax call, the rest of the code is running before it has the var. If I simply add in an alert, things work fine:

var quote_request_id;
  $.ajax({
          type: "POST",
          url: rate_url + '/99/1',
          data: datastring,
          dataType: "html"
  }).done( function(data,status,xhr) {
       quote_request_id = xhr.getResponseHeader('X-QuoteRequest-Id');
  });

I then have other ajax calls that uses the quote_request_id var but it isn't being set. If I simply add in an alert after the block of code above, it works. I realize it's because of the asynchronous behavior of the ajax call. Just need to figure out a way to get the var and use it in the rest of the code.

BlueShoe
  • 693
  • 1
  • 7
  • 8
  • 1
    What you think you need and what you actually need are two different things. What you actually need is to refactor your code to take into account the asynchronous nature of getting the quote request id from the server. – Adam Jenkins Jul 04 '16 at 18:19

1 Answers1

0

Then you don't need AJAX, you need SJAX which is a synchronous communication instead. Add async: false to your ajax object. However, I would suggest you launch the subsequent ajax calls from the success method or done of the first one, so that you have the variable anyway.

Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
  • 1
    But note that doing this is incredibly bad practice and will mean that you get browser warnings appearing in the console. A better solution would be to refactor your code so that it follows async principles. – Rory McCrossan Jul 04 '16 at 18:17