Search code examples
javascriptphphtmlsetvalue

using setvalue to run a loop


HTML:

<section class="clientbox">
    <div class="container">
        <div class="col-lg-10 col-lg-offset-1">
            <h2>WHAT CLIENT SAYS</h2>
            <h4>POSITIVE REVIEWS FOR LOVING PROBLAM.COM </h4>
            <p id="testimonial"><?php echo $alldata[0]['text'] ?></p>
         </div>
    </div>    
</section>

javascript:

<script type="text/javascript">
<?php $i = 1; ?>
    setInterval(function()
        {
            document.getElementById('testimonial').innerHTML = "<?php echo $alldata[$i]['text'] ?>";
            <?php $i++; ?>
        }, 3000);

What actually I am trying to do is change the text of 'testimonial' from values stored in $alldata array every 3 secs.

The problem is that the php variable $i is not getting updated. It stays 1 only.


Solution

  • You mixed the server side logic (PHP) with the client side logic (JavaScript).

    When the client request your web page, PHP render the contents which contains HTML, CSS, JavaScript and some other contents and the web server send these contents to the client side.

    The web browser receives these contents and then execute the JavaScript and render the HTML according to the styles.

    You need to generate all the contents needed by the JavaScript setInterval on the server side, and adjust your JavaScript logic to iterate on these data.

    The logic may looks like the following. I'm not familiar with PHP, not sure if this is valid. The JavaScript doesn't check if all data has been consumed.

    <script type="text/javascript">
        <?php
        function get_data($e) {
            return($e['text']);
        }
        $data = array_map("get_data", $alldata);
        ?>
        var js_alldata = <?php echo json_encode($data) ?>;
        var i = 1;
        setInterval(function()
            {
                document.getElementById('testimonial').innerHTML = js_alldata[i % js_alldata.length];
                i++;
            }, 3000);