Javascript xmlhttprequest asynchoronous call requires alert

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Pallavi R
    New Member
    • Feb 2012
    • 1

    #1

    Javascript xmlhttprequest asynchoronous call requires alert

    In the code below I have to have the alert statement marked by the two *s. Else firefox returns an empty 'temp' even though the 'webtext' is read correctly. How can I remove this requirement?

    Code:
    function getdatalinks(diagnosis,min_age,max_age,gender)
    	{	
    		var temp="";
    		var urii="given URL";
        	
        	if (window.XMLHttpRequest) 
        	{// code for IE7+, Firefox, Chrome, Opera, Safari
        	xmlhttp=new XMLHttpRequest();
    		} 
    		else 
    		{// code for IE6, IE5
        		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    		}
      		
      		xmlhttp.open("GET",urii,true);
    		xmlhttp.send(null);
    		
      		xmlhttp.onreadystatechange=function()
      		{//the request is in ready state but not complete
      			if(xmlhttp.readyState==4 && xmlhttp.status==200)
      			{//request is complete		
      				webtext=String(xmlhttp.responseText);
    				alert(webtext);
    				temp=webtext;
      			}
      		};
    			alert(temp); //**
    			return(temp);
    		
    	}
    Last edited by Dormilich; Feb 23 '12, 04:16 PM. Reason: Please use [CODE] [/CODE] tags when posting code.
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    that is the purpose of a async call. you simply cannot return the value at that point where you do it ... the response is only reliably available in the onreadystatecha nge-callback. so the flow of your code has to consider that and just can proceed from there. call the next function that you need from inside the callback and you are fine.

    Comment

    Working...