Jump to content

How to get server response on first function call?


Recommended Posts

With current code I have to call test() 2 times before i get value. Is there way to make loadXMLDoc return response? or set value of ResponseText on first function call instead of 2nd one? I mean when I first call test() i see empty alert, but when I call it again then I have content returned by server. Is there way to get it on first call?

var ResponseText = ''; function loadXMLDoc(){	var xmlhttp;	if (window.XMLHttpRequest)	{// code for IE7+, Firefox, Chrome, Opera, Safari		xmlhttp=new XMLHttpRequest();	}	else	{// code for IE6, IE5		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");	}	xmlhttp.onreadystatechange=function()	{		if (xmlhttp.readyState==4 && xmlhttp.status==200)		{			ResponseText = xmlhttp.responseText;		}	}	xmlhttp.open("GET","acp.php?a=listusers",true);	xmlhttp.send();} function test(){	alert(ResponseText);}  

Edited by SoItBegins
Link to comment
Share on other sites

The problem is that XMLHttp requests are asynchronous. The rest of your script will continue running before the data has returned. The real solution is to use the response only in the function that is called when a response is received.The easiest asynchronous solution would be this:

if (xmlhttp.readyState==4 && xmlhttp.status==200) {    ResponseText = xmlhttp.responseText;    test();}

Setting the parameter of the open() methos to false causes the request to become synchronous and the browser will freeze until the response is received.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...