0

I am making an ajax request and storing the response as a variable as you can see bellow. My problem is that I need to make sure response is complete and the variable is set before continuing on. I believe this is an issue with async but am unsure as how to correct such an issue. Going off of other posts i adjusted the code bellow to use the $.ajax notation and set async to false however still had issues with the script moving on before var a was set thus i was working with an undefined variable else where. Including a success script and/or callback didn't improve results either.

var a = [];
$(window).load(function () {
    $.get('################', function (response) {
        a.resp = response;
    });

});
LCaraway
  • 1,257
  • 3
  • 20
  • 48
  • 3
    Whatever next you want to do, do it from within the success handler. You can of course call a function from there. – trincot Jun 27 '16 at 20:34
  • Have you tried to use done() function? $.get("###", function(response){}).done(function(data){ //data coming from server response }); – Andrew Ribeiro Jun 27 '16 at 20:35
  • `async:false` is a bad idea. It will lock up the browser....http://api.jquery.com/jQuery.ajax/ – Rick S Jun 27 '16 at 20:36
  • Well `async: false` should work. If it doesn't it means your code is screwed up somewhere else. Post the rest of your code or give more insights. – Radmation Jun 27 '16 at 20:36
  • `async: false` has been deprecated in jQuery since version 1.8. – Heretic Monkey Jun 27 '16 at 20:37
  • @Radmation, ["Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience."](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Synchronous_request) – trincot Jun 27 '16 at 20:38
  • @trincot - does that mean it is async by default now? – Radmation Jun 27 '16 at 20:40
  • It has always been async by default. What do you mean? – trincot Jun 27 '16 at 20:41
  • @trincot Yup your right. I had them mixed up. I meant `async: true` before. – Radmation Jun 27 '16 at 20:42
  • @Radmation The point still stands. It has always been async by default. – dokgu Jun 27 '16 at 20:51
  • Both the .done() and success methods appear to call the functions before the response is done loading. – LCaraway Jun 27 '16 at 20:57
  • "...appear to call the functions before the response is done..." Put some console.log("success run") console.log("done run") type things in there to verify. The success and done should absolutely NOT run before the request finishes. – nurdyguy Jun 27 '16 at 21:08

0 Answers0