Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Sep 2012
    Location
    Buffalo
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Cool Javascript calling PHP

    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:

    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?

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Yeah, you can't do this at all.
    PHP cannot be called by a JS function. So your javascript will always be:
    PHP Code:
    <script>
    function 
    updateDateTime()
    {
    var 
    outputString October 42012 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.

  • #3
    Senior Coder DanInMa's Avatar
    Join Date
    Nov 2010
    Location
    Salem,Ma
    Posts
    1,577
    Thanks
    13
    Thanked 248 Times in 248 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •