0

Possible Duplicate:
How to return AJAX response Text?
How to return the response from an AJAX call from a function?

After whole day without solution to this. I read that this isn't possible or cant be done etc. I did go trough all of topics related, but cant find solution.

So i think my variable in code is out of scope and i cant return it, cant use it.

js file:

function getXMLHttp()
{
  var xmlHttp

  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
        alert("Your browser does not support AJAX!")
        return false;
      }
    }
  }
return xmlHttp;

}



function MakeRequest()
{
  var xmlHttp = getXMLHttp();

 xmlHttp.onreadystatechange = function(){


   if(xmlHttp.readyState == 4)
    {
      var myvar = new Array();
     myvar=JSON.parse(xmlHttp.responseText);

    return myvar;
    }





} 

   xmlHttp.open("GET", "showimage.php", true);
  xmlHttp.send();



}

So here above is ok, its returning value of php script when its finished.

And i want this myvar variable in html file. Tried like this:

 window.onload = function() {
 var myvar = MakeRequest();
 alert (myvar);

} 

It fails, returning undefined value.

Tried also making MakeRequest function as callback function, and then calling it from html like

MakeRequest(function(txt){
});

Then I got response, but can just alert it. I don't want to alert it. I need it to be stored in variable myvar because its needed later in code.

Community
  • 1
  • 1
  • 2
    Welcome to the wonderful world of **async**! You can't do that. – SLaks Jan 13 '13 at 17:21
  • so i need some other solution to connect php and java. i dont want to use false in xmlHttp.open statment. then i could do that? – user1825130 Jan 13 '13 at 17:21
  • 1
    @user1825130: Java? You mean JavaScript... and no, you don't, you just have to use XMLHTTPRequest correctly. – Felix Kling Jan 13 '13 at 17:22
  • yes i mean javascript, thank you felix. didnt came across this topic. will take a look – user1825130 Jan 13 '13 at 17:25
  • Btw `MakeRequest(function(txt){ myvar = txt; });` is perfectly fine as long as the code that needs `myvar` is executed *for sure* after the response was recieved. Any code that *directly* has to work with the response has to go inside the callback (or be invoked from there). It might require restructuring your code, but it's certainly possible. – Felix Kling Jan 13 '13 at 17:26
  • Yes i agree with you, it works when i have alert(myvar); inside of brackets. But when i want to use it in another place its undefined – user1825130 Jan 13 '13 at 17:30

0 Answers0