简体   繁体   中英

how to fetch next/previous rows from database using ajax

I am trying to fetch next previous rows from mysql database to ajax

I managed to do it but i have a problem when i click previous button it always send me back to the first result

<script>
    $(document).ready(function(){
        var card_id = document.getElementById('cardid').value
        $(document).on('click', '#previous', function(){
            $.ajax({
                url:"includes/fetchcards.php",
                method:"POST",
                dataType: 'json',
                data:{card_id:card_id,prev:1},
                success:function(data)
                {

                    $('#cardfront').text(data.front)
                    $('#cardback').text(data.back);
                    card_id = data.id
                    alert(card_id)



                }
            });
        });

        $(document).on('click', '#next', function(){
            $.ajax({
                url:"includes/fetchcards.php",
                method:"POST",
                dataType: 'json',
                data:{card_id:card_id, next:1},
                success:function(data)
                {
                    $('#cardfront').html(data.front)
                    $('#cardback').html(data.back);
                    card_id = data.id
                    alert(card_id)



                }
            });
        });

    });
</script>

php code

<?php
include 'config.php';
if(isset($_POST["card_id"]))
{
    $card_id = $_POST["card_id"];
    if(isset($_POST["next"])){
        $db->where("id", $card_id,  ">") ;
        $flaschcard = $db->getOne('cards') ;
    }
    if(isset($_POST["prev"])){
        $db->where("id", $card_id,  "<") ;
        $flaschcard = $db->getOne('cards') ;
    }
    if(isset($flaschcard)) {
        echo json_encode($flaschcard);
    }
}


I expect that when i click previous button it shows the previous row but it always send me back to the first result

if(isset($_POST["prev"])){
    $db->where("id", $card_id,  "<") ;
    $db->orderBy("id", "desc"); // Reverse the order to fetch the last one
    $flaschcard = $db->getOne('cards') ;
}

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