0
    var req = new XMLHttpRequest();
    req.open("Get","/topjob/php/data.json");
    req.onload = function (){
        var ourData = JSON.parse(req.responseText);
        randerHTML(ourData);
        randerHTML2(ourData);
    req.send();
};

I want to assign responseText to global variable. how can do it

Shenald
  • 143
  • 1
  • 12
  • This might be a useful read https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Musa Jun 07 '18 at 14:27

3 Answers3

0

Global variables are, basically, the properties of the window object.

var req = new XMLHttpRequest();
req.open("Get","/topjob/php/data.json");
req.onload = function (){
    window.myNewVariable = req.responseText;
    var ourData = JSON.parse(req.responseText);
    randerHTML(ourData);
    randerHTML2(ourData);
req.send();
};
Alex
  • 4,621
  • 1
  • 20
  • 30
0

You can just put this:

globalVariable = req.responseText;

anywhere in your code where req.responseText is defined.

But creating such global variables is definitely NOT a good idea. If you need to do so, it means that something's not right with your app's architecture.

htshame
  • 6,599
  • 5
  • 36
  • 56
  • i want to execute for loop when page load. if i added for loop to inside of req.onload = function (){ } its not execute, how can i execute it inside – Shenald Jun 07 '18 at 14:51
0

Declare it just outside the method where this ajax call is written. Making it a global variable is a recipe for introducing unpredictable bugs if the code does not take care of it properly.

var topJobData;
var req = new XMLHttpRequest();
req.open("Get","/topjob/php/data.json");
req.onload = function (){
    topJobData = req.responseText;
    var ourData = JSON.parse(req.responseText);
    randerHTML(ourData);
    randerHTML2(ourData);
    req.send();
};
gargkshitiz
  • 2,130
  • 17
  • 19