SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    How to mix Javascript and PHP?

    I want to call a Javascript function in PHP. This does not execute the function but shows the text on the screen:

    Code:
    	if ((strlen($chooseYear) < 1)) { $chooseYear = date('Y');
    echo "messageDefaultYearInserted()"; 
    	}
    How do I execute a function in a case like this? In this case, the function will write a message in innerHTML in a span.
    Steve Husting

  2. #2
    SitePoint Enthusiast
    Join Date
    Mar 2011
    Posts
    70
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    You can't call a javascript function from php. PHP is processed on the server and passed to the browser as a complete rendered page. Javascript is executed by the browser after the page has already been returned to the browser.

    Why not create 'messageDefaultYearInserted()' in your php script and call it that way?

  3. #3
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I'm rusty with my PHP! I'll try that next. Thanks for helping.
    Steve Husting

  4. #4
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    This did not work (text did not appear):

    Code:
    <?php
    /* PHP FUNCTIONS */
    function messageDefaultYearInserted(){
    echo "document.getElementById('messages').innerHTML = '<p>Current year displayed.</p>'";
    }
    ?>
    
    <!-- warning messages displayed here -->
    <div id="messages" style="color:red; clear:left;"></div>
    
    <?php
    [...php code...]
    	if ((strlen($chooseYear) < 4)) { $chooseYear = date('Y');messageDefaultYearInserted();}
    ?>
    Am I warm?
    Steve Husting

  5. #5
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,384
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    This works (adding the <script> tags):

    function messageNotWithinRange() {
    echo "<script>document.getElementById('messages').innerHTML = '<p>What you entered falls outside the range allowed in the Year field.</p>'</script>";
    }
    Steve Husting


Bookmarks

Posting Permissions

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