Jump to content

Ajax Returnvalues To Variable


Redroest
 Share

Recommended Posts

Hey people I am trying to make an AJAX object that returns its values to a variable. Every time when I try to alert the output from the server it says undefined or [Object]. When I alert the xmlhttp.responseText within the sendRequest function it works!

var XMLHttpFactories = [	function () {return new XMLHttpRequest()},	function () {return new ActiveXObject("Msxml2.XMLHTTP")},	function () {return new ActiveXObject("Msxml3.XMLHTTP")},	function () {return new ActiveXObject("Microsoft.XMLHTTP")}];function GetXmlHttpObject() {  var xmlhttp = false;  for (var i=0;i<XMLHttpFactories.length;i++) 	{	try 		{	  xmlhttp = XMLHttpFactories[i]();	}	catch (e) 		{	  continue;	}	break;  }  return xmlhttp;}function sendRequest(url,postData){  //alert('sendRequest');  var xmlhttp = GetXmlHttpObject();  if (!xmlhttp) return;  var method = (postData) ? "POST" : "GET";  xmlhttp.open(method,url,true);  xmlhttp.setRequestHeader('User-Agent','XMLHTTP/1.0');	//xmlhttp.setRequestHeader('X-AJAX', 'True');  if (postData)	xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');  xmlhttp.onreadystatechange = function ()	{	//alert('readyState: '  + xmlhttp.readyState);	if (xmlhttp.readyState != 4) return;	if (xmlhttp.status != 200 && xmlhttp.status != 304)		{	  alert('HTTP error ' + req.status);	  return;	}	  this response = xmlhttp;  }  if (xmlhttp.readyState == 4) return;  xmlhttp.send(postData);}

Call users values (for example)

function getServerUsers(username, password){  var ServerValues = sendrequest('users.php', username='+username+'&password='+password);  alert(ServerValues.responseText);}

Im not very familier with javascript but I know that it has to be something like this to make it work. The Serverside script works and outputs. I always used a callback function but I think it can be shorter. So how to make this work?

Link to comment
Share on other sites

You need to use a callback function, the sendrequest function does not return a value so you can't set any variable with the output from sendrequest. You need to use a callback. If that's the ajax code I posted in the sticky thread, it started with a callback.

Link to comment
Share on other sites

That does work, but it may not do what you want. If you want the sendrequest function to return the output from the server, that's not going to happen, at least not with an asynchronous request. You may be able to do that using a synchronous request instead, but if you do that your code will pause and wait until the response comes back from the server.

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
 Share

×
×
  • Create New...