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