rainerbrunotte
rainerbrunotte

Reputation: 907

Use PHP to conditionally render a Javascript function call in the browser

I have a button which successfully triggers a "load more" on click. Once it is clicked, a SESSION variable is set, so that when the user reloads the page, the new posts should appear loaded already, so that the user does not need to click again "load more".

I would thus like to render the same "load more" Javascript function in a PHP IF statement, according if a SESSION or COOKIE is set or not:

<?php
if ((isset($_SESSION['isloaded'])) || (isset($_COOKIE['isloaded']))){
echo '<script>loadmore(\'posts\');</script>';
}
else {
echo '<a href="#" onClick="return false" onmousedown="javascript:loadmore(\'posts\');" class="btn btn-primary" id="load-more-btn">Load More</a>';
}
?>

However the Javascript does not get triggered once the page is rendered. What am I doing wrong?

Upvotes: 1

Views: 1357

Answers (2)

JimmyB
JimmyB

Reputation: 12610

To have your JavaScript run automatically, you can use the onLoad event, like

<body onload="loadmore('posts')">
...
</body>

or maybe

<body onload="conditionally_loadmore('posts')">
<?php
if ((isset($_SESSION['isloaded'])) || (isset($_COOKIE['isloaded']))){

    // Only have the function do something if we really want to.
    echo '<script>function conditionally_loadmore(s) {';
    echo ' loadmore(s); ';
    echo '}</script>';
}
else {

    echo '<script>function conditionally_loadmore(s) {';
    echo ' // Do nothing. ';
    echo '}</script>';

    echo '<a href="#" onClick="return false" onmousedown="javascript:loadmore(\'posts\');" class="btn btn-primary" id="load-more-btn">Load More</a>';
}
?>

or, as @Astaroth suggested:

<body
    <?php
      if ((isset($_SESSION['isloaded'])) || (isset($_COOKIE['isloaded']))) {
        echo 'onload="loadmore(\'posts\')"';
      }
    ?>
>...

Upvotes: 0

Pimmol
Pimmol

Reputation: 1871

As @Austin and @Angry Coder said, check your console for errors.

Also, make sure function loadmore() is defined before it's called. So either place the function declaration above the loadmore('posts'); call or add the call on a onload or something similar.

An other thing, maybe for clearness you can write your code like (but it's an opinion):

<?php  if ((isset($_SESSION['isloaded'])) || (isset($_COOKIE['isloaded']))) { ?>
        <script>loadmore('posts');</script>
<?php } else { ?>
        <a href="#" onClick="return false" onmousedown="javascript:loadmore('posts');" class="btn btn-primary" id="load-more-btn">Load More</a>
 <?php } ?>

Upvotes: 3

Related Questions