I have the following simple example:

<script>
var titel = new Array(1,2);
for(var i=0; i< titel.length; i++){
alert(titel[i]);
window.setTimeout("document.getElementById('main').innerHTML = titel[i]",2000);
}
</script>

The id main is in the body tag.

Question: Why will the title[i] be shown in the alert, but not in the setTimeout? I get a undefined in the body Tag
Thanks in advance

Comments

robertdouglass’s picture

var titel = new Array(1,2);
for(key in titel){
alert(titel[key]);
window.setTimeout("document.getElementById('main').innerHTML = titel[key]",2000);
}

- Robert Douglass

-----
My Drupal book: Building Online Communities with Drupal, phpBB and WordPress

Thox’s picture

After the 2 seconds is up, i will be 2... and both timeouts will do the same thing. Just guessing

Steven’s picture

Your 'titel' variable is probably not in scope when the timeout fires. Use a closure instead:

var string = titel[i];
window.setTimeout(function() {
  document.getElementById('main').innerHTML = string;
}, 2000);

--
If you have a problem, please search before posting a question.

wickus’s picture

I assume the whole thing is still within a for loop? At least I tried it with this and it still showed up the last piece of content in the array.

I try to refresh only the div main in my drupal page. I found the ajax.updater in prototype but it seems to refresh full nodes or pages into the given part. So it looks bad when the full node with the surrounding blocks will be reloaded in the div main .
I try to set up a database where folks can put in the node id and a time to refresh, with this node id they get the title and body from the node_revisions table which shall be refreshed in this given time in the div "main" part of the drupal page. Maybe somebody has a solution for this?

Thanks
Wickus
---
Join the virtual march to stop global warming.
http://www.stopglobalwarming.org/marchers/?142067

pears447’s picture

Try this. Put this code in your <head>:

var titel = new Array(1,2);
var i = -1;

function advance(){
i++;
if(i < titel.length){
alert(titel[i]);
document.getElementById('main').innerHTML = titel[i];
window.setTimeout("advance()", 2000);
}
}

Call the function advance() when the page loads. This script starts changing the value of main right away, instead of waiting two seconds. This would be easy to change with another setTimeout().

wickus’s picture

wow groovy, that could probably help me. thanx a lot

---
Join the virtual march to stop global warming.
http://www.stopglobalwarming.org/marchers/?142067

wickus’s picture

why is the german Ü = ü when first urlencode it and then try to decode it again? seems to be pretty weird to me?
Had the problem with the php db data I passed to js, so I rawurlencode it before and then in the innerHTML I unescape the stuff again and it came out like this. Tried to replace it with the js replace function but no change.

---
Join the virtual march to stop global warming.
http://www.stopglobalwarming.org/marchers/?142067

pears447’s picture

I know barely anything about encoding/character escaping, but since no one else seems to be writing back I thought I'd post. Would it make any difference if you used base64 (base64_encode()) or uuencode (convert_uuencode(), PHP 5 only) encoding instead of URL encoding? There are many Javascript base64 decoder scripts available. I'm guessing the problem is that you're using a Unicode character which is not being handled properly by the encoder/decoder you're using.

wickus’s picture

due to pears447 help with his advance function I finally got it done, sorry it took so long to post the stuff here:
unfortunately I can't upload the files here so I try to include the code:

You need to create a table, in my case I called it autorefresh,

DROP TABLE IF EXISTS `autorefresh`;
CREATE TABLE `autorefresh` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `refresh` tinyint(4) NOT NULL default '0',
  `nid` int(11) NOT NULL default '0',
  `reihenfolge` smallint(6) NOT NULL default '0',
  `online` char(1) NOT NULL default '',
  `beschreibung` varchar(255) NOT NULL default '',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Watch out if you have a table called like this, it will be dropped due to the first line.

The following code is the file autorefresh.php which will gather the data from the node_revisions table. This file will be called by the sndReq() Function from the ajax js functions file I called it mwajax.js (the utf8_encode will be needed when you have german or whatever specialchars in your language):

<?php
mysql_connect("server","user","pass");
mysql_select_db("db");
$sql = mysql_query("select title, body from node_revisions where nid=".$_REQUEST['nid']." order by vid desc");
$_ROW = mysql_fetch_array($sql);
echo "<h3><a href='http://www.yourdomain.com' target='_top'>Startseite</a></h3><h1 class='title' style='color: #c00'>".utf8_encode($_ROW['title'])."</h1><div class='content'><p>".utf8_encode($_ROW['body'])."</p></div>";
?>

In the first line of the page.tpl.php I put the following code: (I think I put it in there because it was corresponding with some JS code you will see later in the head of the page.tpl.php

<?php
//Beginning of page.tpl.php or extra functionsfile 
	$n = "";
  $r = "";
  $i = 0;
	$sql = mysql_query("select refresh, nid from autorefresh where online = '1' order by reihenfolge");
  while($_ROW = mysql_fetch_array($sql)){
  	$i++;
  	$n .= $_ROW['nid'];
    $r .= $_ROW['refresh'];
    if($i < mysql_num_rows($sql)){
    	$n .= ",";
    	$r .= ",";
    }
  }
?>

In the HEAD section I added first my ajax js functions file

<script language='JavaScript' src='./javas/mwajax.js'></script>

The content of this file (mwajax.js) is :

//AUTOREFRESH FUER DIV "MAIN"

var resObject = null;
var i = -1;

function erzXMLHttpRequestObject(){
	var resObject = null;
  try {
  	resObject = new ActiveXObject("Microsoft.XMLHTTP");
  }
  catch(Error){
  	try {
  		resObject = new ActiveXObject("MSXML2.XMLHTTP");
    }
    catch(Error){
    	try {
      	resObject = new XMLHttpRequest();
      }
      catch(Error){
      	resObject = "Bummer";
      }
    }
  }
  return resObject;
}

function sndReq(seitenid){
  resObject.open('get', 'autorefresh.php?nid='+seitenid, true);
  resObject.onreadystatechange = handleResponse;
  resObject.send(null);
}

function handleResponse(){
	if(resObject.readyState == 4){
  	document.getElementById("main").innerHTML = resObject.responseText;
  }
}

resObject=erzXMLHttpRequestObject();

Beside this I added the following code in the HEAD

<script language="JavaScript">


//the following 6 lines just check the startpage. if you don't do this the refresh will pretty run //every time you load a page
 
 	var d1= "http://www.yourdomain.de";
	var d2= "http://www.yourdomain.de/index.php";
  var d3= "http://www.yourdomain.de/";
	if(document.URL == d1) {  i=-1; } else  {  i=1000; }	
	if((document.URL == d2) && (i == 1000)) {  i=-1; }
	if((document.URL == d3) && (i == 1000)) {  i=-1; }
	var nid = "<?php echo $n; ?>";
	var ref = "<?php echo $r; ?>";
	var n = nid.split(",");
	var r = ref.split(",");
	var anz = n.length;
	var i = 0;

//Thanks to pears447 for this function

	function advance(){
		i++;
		if(i < anz){
			sndReq(n[i]);
			window.setTimeout("advance()", r[i]*1000);
		}	
	}
  
  window.onload = advance;
</script>

I hope you can find some use in it, sorry its my first time to post some code. I tried of course the ajax.refresh from the prototype.js but in there it seems that it refreshes the whole node, which is not so nice especially when you load the whole node again in the div main (the blocks appear double then on the left and right. And why loading the whole node with the blocks when you can only load the main part. The only problem I have is that the refreshed pages are not editable when you logged in. You need to look them up through the admin menu. Maybe somebody gets a solution for this.

Greetings and thanks for you patience.
---
Join the virtual march to stop global warming.
http://www.stopglobalwarming.org/marchers/?142067