rain13 Posted July 15, 2012 Share Posted July 15, 2012 (edited) 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 July 15, 2012 by SoItBegins Link to comment Share on other sites More sharing options...
Don E Posted July 15, 2012 Share Posted July 15, 2012 Is there more to the code than what's being displayed above? Anyhow, as for the alert, remove the single quotes from ResponseText and see if you get different results. Link to comment Share on other sites More sharing options...
rain13 Posted July 15, 2012 Author Share Posted July 15, 2012 Oh sorry, just created test function for that post to demonstrate how i want it to work. The solution was to set 3rd parameter of xmlhttp.open from true to false. Link to comment Share on other sites More sharing options...
Ingolme Posted July 16, 2012 Share Posted July 16, 2012 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 More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now