简体   繁体   中英

PHP Counting with AJAX Request

I'm trying to counting a SESSION variable, but i don't want that the user seeing any refreshes.

my problem with the code below is that, it change only ones and then its needed a refresh. How can i do this without any refreshes?

test page:

     <?php session_start(); ?>
            <script src="../../../common/js/jquery-1.11.2.min.js"></script>
        <script src="../../../common/js/jquery.touchwipe.min.js"></script>
    <?php
    if(empty($_SESSION['counter'])){
    $_SESSION['counter'] = 1;
    }
    $count = $_SESSION['counter'];


    ?>
    <div id="main"><?= $count; ?></div>
    <button id="detailed">Link</button>

    <script type="text/javascript">
        $(document).ready(function(){
            $(document).on('click','#detailed',function(){
                var count = "<?= $count ?>";
                count++;
                $.ajax({
                    type: "POST",
                    url: "test.php",
                    data: {countertje: count},
                    success:function(data){
                        $('#main').html(data);
                        console.log(data);
                    }

                });
            })

        });
    </script>

do_ajax.php

    <?php
    session_start();
    $_SESSION['counter'] = $_POST['countertje'];
    echo $_SESSION['counter'];
    ?>

Something you could use in javascript

 var count = $('#main').val();

instead of following :

var count = "<?= $count ?>";

Writting PHP code inside javascript isnt good idea!

<script type="text/javascript">
        var count = "<?= $count ?>";
        $(document).ready(function(){
            $(document).on('click','#detailed',function(){
                count++;
                $.ajax({
                    type: "POST",
                    url: "test.php",
                    data: {countertje: count},
                    success:function(data){
                        $('#main').html(data);
                        console.log(data);
                    }

                });
            })

        });
    </script>

count should be a global variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM