0

I tried playing with AJAX a bit. This is just the chunk of JavaScript I got.

// FIRST TIME REQUIREMENT
var interAction = new XMLHttpRequest();
var responseAJAX;

interAction.onreadystatechange = function() {
    if (interAction.readyState == 4 && interAction.status == 200) {
        alert(interAction.responseText);
        responseAJAX = interAction.responseText;
    }
}
alert("inside");
interAction.open("GET", "ss-controller.php?req=freshStart", true);
interAction.send();

alert("This is my response: " + responseAJAX);

Firstly I thought that interAction.onreadystatechange = function() encapsulated the variable, but I did declare it in global scope (second row). I do get "testxxx" as response from alert(interAction.responseText); and then I get "This is my response: undefined" from last row.

2
Contributors
3
Replies
11
Views
2 Years
Discussion Span
Last Post by pritaeas
0

The alert is triggered before the response is received. The code keeps running while your asynchronous call is waiting for a response.

Edited by pritaeas

0

How could I save variable in the best way? I need to for my further code to work. I could make it run a function, after answer has been received, but, it's strange that I had to contain actions in a function, when it's not required. Or maybe I could make JavaScript halt for a bit until answer is received?

0

I could make it run a function

That would be the correct way when you're programming asynchronously. If you want a responsive site then this is the way to go, blocking IMO is not (you can't predict how long a call will take). You just need to get used to it.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.