-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" 
Omer Farooq
  • 3,754
  • 6
  • 31
  • 60

1 Answers1

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);
}
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
  • 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. – Omer Farooq Apr 06 '18 at 18:46
  • It's not a scope problem it's a timing problem – Sebastian Speitel Apr 06 '18 at 18:51
  • You could use the answer to this (https://stackoverflow.com/questions/6685249/jquery-performing-synchronous-ajax-requests) to synchonously use the ajax call – Sebastian Speitel Apr 06 '18 at 18:53