Is it possible to load the output from a script into a variable using Ajax?

I have an ajax function that I’ve written which works well, however it has one limitation which is that it has to always output the ajax.responseText to an element. I’m trying to make it so I can just retrieve some data (a string) over an ajax call and put that immediately into a variable. Here is what I got so far.

    function ajax_read(url,method)
    {
      var ajax=new XMLHttpRequest();
      ajax.onreadystatechange=function() 
      {
        if (ajax.readyState==4 && ajax.status==200) 
        {
          console.log(ajax.responseText);
          return ajax.responseText;
        }
      }
      ajax.open(method,url,true);
      ajax.send();
    }

Now interestingly enough, it will console.log the output from the script, but when I try to return the response into a variable it just says undefined when I try to use the variable.

alert(ajax_read('test.html','GET'));

test.html contains one word “test”, and it console.log’s correctly, but displays undefined when trying to alert() it.

Any tips? Mucho appreciated :smiley:

This will not work because Ajax calls are asynchronous which means that they don’t immediately return a value after you execute them.

One way to get around this would be to pass in a callback which is executed once the Ajax request has successfully completed.

function ajax_read(url,method, callback)
{
  var ajax=new XMLHttpRequest();
  ajax.onreadystatechange=function()
  {
    if (ajax.readyState==4 && ajax.status==200)
    {
      console.log(ajax.responseText);
      callback(ajax.responseText);
    }
  }
  ajax.open(method,url,true);
  ajax.send();
}

function displayValue(val){
  alert(val);
}

ajax_read('test.html','GET', displayValue);

Or in modern browsers, use the Fetch API:

fetch('test.html').then(function(response) {
  return response.text().then(function(text) {
    alert(text);
  });
});
1 Like

Beauty. Thank you!

No worries :slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.