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.

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

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?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.