PDA

View Full Version : Javascript outputting "undefined" in the html



phpchick
03-14-2012, 05:12 PM
<script type="text/javascript">
function loadText()
{
var t1=setTimeout("document.getElementById('data').innerHTML='<center><img style=\"margin-top:30px;\" src=\"loading.gif\" /></center>'",0000);
var t2=setTimeout("document.getElementById('data').innerHTML='THEPAGE'",6000)
}
</script>

The above is in the header, and I'm calling it in the html.


<script type="text/javascript">
document.write(loadText());
</script>

in the page it displays properly, but then it also says "undefined" not sure why? anyone have any ideas?

jmrker
03-14-2012, 05:28 PM
The script in the <head> section is probably being executed BEFORE the 'data' element in the <body> section is available.
Try moving the <script> in the <head> to just before the last </body> tag.

Plus, I'm not sure that is a valid function to execute in the setTimeout command (???)

Logic Ali
03-14-2012, 05:31 PM
You don't need the document.write statement, which is printing the function's return value.

phpchick
03-14-2012, 05:34 PM
You don't need the document.write statement, which is printing the function's return value.

correct.

I just did

loadText() by itself and the undefined has now disappeared. Thank you.

felgall
03-14-2012, 07:22 PM
setTimeout("document.getElementById('data').innerHTML='THEPAGE'",6000)

should read:

setTimeout(function() {document.getElementById('data').innerHTML='THEPAGE'},6000)

setTimeout wants a function - NOT as string of text. The only reason it is currently working is because it uses an implicit eval() to convert what you have into the function the call expects.