Jump to content
Sign in to follow this  
mobone

Ajax And Settimeout

Recommended Posts

I'm trying to send a setTimeout function to the ajax that requested the page. But it seems to not be setting the new timeout.This runs for .5 seconds and prints 19, as it should, but it should continue counting down. If I change the first timeout to setinterval, it counts down as I want it to. The new timer is not running. Grr! -New to ajax.Oh by the way. When requesting the page I request "test.php?load=1" to get it set up for the first time.

<?phpsession_start();//just the usual http_request code.function printajax(){	echo "<html><head><script language='javascript' type='text/javascript'>	function getHTTPObject(){	if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');	else if (window.XMLHttpRequest) return new XMLHttpRequest();	else {		alert('Your browser does not support AJAX.');		return null;   	}	}  function outputDefender() {if(httpObject.readyState == 4) document.getElementById('DefenderOutput').innerHTML = httpObject.responseText;}function doWork(){		httpObject = getHTTPObject();	if (httpObject != null) {		httpObject.open('GET', 'test.php', true);		httpObject.send(null); 		httpObject.onreadystatechange = outputDefender;	}}var httpObject = null;</script>";}if ($load) {	printajax();	$_SESSION['doug']=20;	unset($load);	echo "</head><body><span id='DefenderOutput' />";	echo "<script language='javascript' type='text/javascript'>setTimeout('doWork()', 500);</script>";	exit;} else {	$_SESSION['doug']--;	echo $_SESSION['doug']."<script language='javascript' type='text/javascript'>setTimeout('doWork()', 500);</script>";}?>

Can I not pass a script call as the return to the httpRequest?

Edited by Mobone

Share this post


Link to post
Share on other sites

Yeah, you can send whatever you want back. But it's not going to treat it as Javascript code and execute it, it's just text. If you want to send it Javascript code to execute, leave out the HTML tags and just send a string of Javascript, and you can use eval to execute it. You should be aware that there might be security implications with just sending the browser a piece of arbitrary code to execute, but those are limited by the fact that the code is running on the client.

Edited by justsomeguy

Share this post


Link to post
Share on other sites

Well I edited it, and it's still not working. Prints three, then prints 19, and then nothing. I want the eval to call the doWork function again.

<?phpsession_start();function printajax(){	echo "<head><script language='javascript' type='text/javascript'>	function getHTTPObject(){	if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');	else if (window.XMLHttpRequest) return new XMLHttpRequest();	else {		alert('Your browser does not support AJAX.');		return null;	   }	}  function outputDefender() {	if(httpObject.readyState == 4) {		eval('httpObject.responseText');		document.getElementById('DefenderOutput').innerHTML = httpObject.responseText;	}}function doWork(){		httpObject = getHTTPObject();	if (httpObject != null) {		httpObject.open('GET', 'test.php', true);		httpObject.send(null); 		httpObject.onreadystatechange = outputDefender;	}}var httpObject = null;</script>";}if ($load) {	printajax();	$_SESSION['doug']=20;	unset($load);		echo "<script language='javascript' type='text/javascript'>setTimeout('doWork()', 500);</script>";	echo "</head><body><span id='DefenderOutput'>three</span>";	exit;} else {	$_SESSION['doug']--;	echo $_SESSION['doug'];	echo "doWork()";}?>

Share this post


Link to post
Share on other sites

You're sending back a bunch of HTML tags. If you want to use eval, you only send Javascript. Eval doesn't work with HTML tags, only Javascript. Also, don't quote the variable name that you're sending to eval, when you quote something it treats it as a static string instead of a variable name.

Edited by justsomeguy

Share this post


Link to post
Share on other sites

Yea I still don't get it. If I don't include the script JavaScript tags it literally prints setTimeout('doWork()', 500); to the screen.

<?phpsession_start();function printajax(){	echo "<script language='javascript' type='text/javascript'>	function getHTTPObject(){	http = window.XMLHttpRequest ? new XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP'): null);	return http;	}  	function outputDefender() {		if(httpObject.readyState == 4) {			document.getElementById('DefenderOutput').innerHTML = httpObject.responseText;		}	}	function doWork(){			httpObject = getHTTPObject();		if (httpObject != null) {			httpObject.open('POST', 'test.php', true);			httpObject.send(null); 			httpObject.onreadystatechange = outputDefender;		}	}var httpObject = null;</script>";}echo "<body><span id='DefenderOutput'></span></body>";if ($load) {	printajax();	$_SESSION['doug']=20;	unset($load);		echo "<script language='javascript' type='text/javascript'>setTimeout('doWork()', 500);</script>";	exit;	} else {	$_SESSION['doug']--;	echo $_SESSION[doug];	echo "<script language='javascript' type='text/javascript'>setTimeout('doWork()', 500);</script>";}?>

look at http://75.73.157.139/magicbattle/test.php?load=1 for a demoYour help is much appreciated.

Edited by Mobone

Share this post


Link to post
Share on other sites

You shouldn't be printing the responseText at all. This is code in the response, not text, right? You don't want to print the code, you want to execute it. So you don't print anything, you just use eval on the code returned in responseText.

Share this post


Link to post
Share on other sites
You shouldn't be printing the responseText at all. This is code in the response, not text, right? You don't want to print the code, you want to execute it. So you don't print anything, you just use eval on the code returned in responseText.
So I'd have one block requesting the timer, another requesting the data, and two sets of both blocks, for both attacker and defender. Isn't there an easier way? I want the timers to be separate so one person can slow the others attack rate.

Share this post


Link to post
Share on other sites

You can return several pieces of data at once, that's what most people use JSON for. JSON is the native Javascript object notation, you can have PHP return a JSON structure and use that in the Javascript code to access the different pieces of data. Recent versions of PHP have a function called json_encode that will turn a PHP array into a JSON structure. In Javascript you use eval to turn the text of the structure into an actual data structure (another array), and then you can access all the data from there. There's more information about JSON at json.org.For example, here's the response of an ajax request for one of my applications where it's getting the data for the last thing the user did:

{"success":true,"errors":[],"data":{"last_login":"Monday June 29th, 2009","last_ip":"207.108.195.60","period":"less than a day","prev_launch":true,"title":"Field Services Certification Test (May 2009)","last_launch":"6-29-2009 10:18am","start_date":"5-21-2009 11:45am","complete_date":"","time":"376","score":"39","counter":"44"}}

So that's the raw JSON data. The Javascript uses eval to turn that into an object:var obj = eval('(' + json + ')');And then it can access the various properties. So the JSON response has a property called "success" with the value true. So after doing the eval above, obj.success would be true. It has a property called "errors" that's just an empty array (array syntax is the square brackets), so obj.errors.length is 0. It has a property called "data" that's another object that has a bunch of properties about what the user did last. So obj.data.last_ip would be "207.108.195.60", for example. obj.data.time would be "376".So you can use the JSON format to send several pieces of data back to the server. You can have one property that contains Javascript code to execute, and other properties that contain your various counters or whatever you want to update the page with. In PHP, you just create an associative array with the different elements. So the PHP array to produce the JSON structure above would look like this:

$obj = array(  'success' => true,  'errors' => array(),  'data' => array(	'last_login' => 'Monday June 29th, 2009',	'last_ip' => '207.108.195.60',	'period' => 'less than a day',	'prev_launch' => true,	'title' => 'Field Services Certification Test (May 2009)',	'last_launch' => '6-29-2009 10:18am',	'start_date' => '5-21'2009 11:45am',	'complete_date' => '',	'time' => 376,	'score' => 39,	'counter' => 44  ));echo json_encode($obj);

Share this post


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...
Sign in to follow this  

×
×
  • Create New...