-3

I have an ajax request where i have a variable that i need to get outside the function. For some reason i am not able to get the values outside the function. For simplicity i am changing my function.

        var myEvents = "hi";
        $.ajax({
            url: 'http://mywebsite.com/events',
            type: "post",
            success: function (response) {
                myEvents = 'hello';
            }
        });

        alert(myEvents); // shows "hi" but i want it to show "hello" 
5
  • it's because alert() runs before your success callback Apr 6, 2018 at 18:15
  • 1
    ... success: function (response) { myEvents = 'hello'; alert(myEvents);} ... Apr 6, 2018 at 18:16
  • @BenceFarkas yes you are right. But how can i get this variable in the main javascript? Apr 6, 2018 at 18:43
  • @BenceFarkas thanks mate, i have been struggling with this for a few days but i knew there has to be a way to achieve this :) Apr 6, 2018 at 18:50

1 Answer 1

0

The alert() is called before the success callback you could enclode it in a function and call it in the callback:

var myEvents = "hi";
$.ajax({
  url: 'http://mywebsite.com/events',
  type: "post",
  success: function(response) {
    myEvents = 'hello';
    func();
  }
});

function func() {
  alert(myEvents);
}
3
  • ok i understand it, but there is a lot of code and functions that are going to execute once the response is achieved. So, its not just a simple alert, there are lots of lines of code and functions. So I dont think it will be possible to bring all my code and functions inside the new function that you have created. There has to be a way to bring the scope the main js function. Apr 6, 2018 at 18:46
  • It's not a scope problem it's a timing problem Apr 6, 2018 at 18:51
  • You could use the answer to this (stackoverflow.com/questions/6685249/…) to synchonously use the ajax call Apr 6, 2018 at 18:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.