0

Question from begginer one. By the AJAX function i'm getting an array in JSON from my script. In the example i want to save responseText (array) in global variable because of my need to use it in another function(s). And I just cannot. I hope there is a way to do it but I cannot find one.

var out;
var arr; //global variable

function ajax(kat1) {
if (kat1 == "") {
    document.getElementById("div1").innerHTML = "";
    return;
} else { 
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

            arr=JSON.parse(this.responseText); //here might be the problem
        }
    }
    xmlhttp.open("GET","script.php?q="+kat1,true);
    xmlhttp.send();
 }
}




function show(response, i)
{
var arr1 = arr;
out = "Question"+arr1[i].id+": "+arr1[i].question+"? ";
document.getElementById("quizblock10").innerHTML = out;
}
  • 1
    What do you mean you "just cannot"? – Carcigenicate Dec 13 '16 at 05:11
  • You can store the data returned from your AJAX call in localStorage. When calling another function (such as `show()` in your example), check the localStorage and then act on the data if it exists. Alternatively, you can always make a new AJAX call when calling `show()`. – Terry Dec 13 '16 at 05:12
  • 2
    Is it [__"How do I return the response from an asynchronous call?"__](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) ? – Rayon Dec 13 '16 at 05:14
  • 1
    When are you calling `show()`? Is it before the ajax call has completed? – asprin Dec 13 '16 at 05:16
  • 1
    It is a question of timing. Any values that become available in an asynchronous callback can only be used inside that callback, or functions whose execution is triggered by that callback. (Probably the most common JS duplicate question.) – Amadan Dec 13 '16 at 05:16
  • Why do you need a global variable? Why can't you just pass the response *to* `show`? – Felix Kling Dec 13 '16 at 05:17
  • 1
    @Terry: There doesn't seem to be any benefit from using local storage here. – Felix Kling Dec 13 '16 at 05:17

0 Answers0