...

View Full Version : Javascript calling PHP



failbot8000
10-04-2012, 06:50 PM
Hello,

I am trying to write a javascript function to periodically update a div element. I want to use PHP to get the actual information. I know the periodic update works, but I can't get anything to display.

My code:




<script>
function updateDateTime()
{

<?php
ob_start();
$today = getdate();
echo $today[month] . ' ' . $today[mday] . ', ' . $today[year] . ' ' . ($today[hours] >= 12 ? $today[hours] - 12 : $today[hours]) . ':' . ($today[minutes] < 10 ? ('0' . $today[minutes]) : $today[minutes]) . ($today[hours] >= 12 ? 'pm' : 'am');
$string=ob_get_contents();
ob_end_clean();
print("var outputString = " . $string . " ;");
print("document.getElementById('datediv').innerHMTL=outputString;");
?>

}

var int=self.setInterval(function(){clock()},1000);
function clock()
{
updateDateTime();
}

</script>


Any ideas?

Fou-Lu
10-04-2012, 07:17 PM
Yeah, you can't do this at all.
PHP cannot be called by a JS function. So your javascript will always be:


<script>
function updateDateTime()
{
var outputString = October 4, 2012 6:06pm;
document.getElementById('datediv').innerHMTL=outputString;
}

var int=self.setInterval(function(){clock()},1000);
function clock()
{
updateDateTime();
}

</script>


To have PHP called, you need to implement an AJAX solution and call a PHP script in the background. I don't know if I'd recommend doing that every second, and for a clock that should all be done in the client side, not the server side. The server side can take responsibility of providing the initial time if you are looking for server specific time instead of a client time.

DanInMa
10-04-2012, 08:19 PM
do a forum search for "refresh div ajax" and you will get quite a few examples to learn from. It's a fairly common task so there are alot of examples.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum