Jump to content

Wrong function return


Recommended Posts

I want the function checkuser() to return a true/false status based on the server response, but the script returns to inter function of checkuser().

function checkuser(user) { if (window.XMLHttpRequest) {  xmlhttp=new XMLHttpRequest(); } else {  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }xmlhttp.onreadystatechange=function()  {  if (xmlhttp.readyState==4 && xmlhttp.status==200)	{	alert(xmlhttp.responseText);	if(xmlhttp.responseText == 'usertaken') {	 alert('ifok');	 return(true);	}	else {	 return(false);	}	}  }xmlhttp.open("GET","index.php?act=isusertaken&user=" + user,true);xmlhttp.send();}

Edited by Cod-nes
Link to post
Share on other sites

You'll have to rethink what you're doing. You'll have to do whatever you want to happen after the request in the onreadystatechage function. This may include calling different other functions (which may be passed as an argument to checkuser() for example), but they need to be called at onreadystatechange.

Link to post
Share on other sites
Thanks. I have a question. Can we do a return function with the response text after xmlhttp.send() or is that not allowed?
are you asking if you can pass the response text to a function by passing it as an argument? (yes, you can)
Link to post
Share on other sites
are you asking if you can pass the response text to a function by passing it as an argument? (yes, you can)
I don't think that's what he's asking... he's still trying to make checkuser() return.You can make the whole request process syncronous, insead of asyncronous, but this means checkuser() will block out everything during the request. To do that, just change the third argument on the open() method, like:
xmlhttp.open("GET","index.php?act=isusertaken&user=" + user,false);

Once that is done, you can move all of your code outside of onreadystatechange, and right after send(), like:

xmlhttp.open("GET","index.php?act=isusertaken&user=" + user,true);xmlhttp.send();	if(xmlhttp.responseText == 'usertaken') {	 alert('ifok');	 return(true);	}	else {	 return(false);	}

Again - this has MAJOR performance implications. It will make checkuser() take a really long time, and nothing else will be doable before that function is finished. The asyncronous approach you were using before didn't have that problem - no matter how long checkuser() takes, other JavaScript would also be active, and users would not be blocked while they wait.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...