Home > Net >  Get information from the database without refreshing the page
Get information from the database without refreshing the page

Time:03-07

I am developing a program. In the store section, we display products for users I want you to see that product when a user is browsing the site and a new product has been added to the site without refreshing the page

I have come and refresh the contents of the store section every few seconds with the setInterval method, but it does not work for me

<div id="parnet" >
        <p id="players">
        <?php foreach ($players as $player) { ?>
        <div  >
            <div >
                <div >
                    <div >
                        <div >
                            <div >
                                <div >
                                    <img  src="<?=baseUrl()?>/upload/images/players/<?=$player['image']?>" alt="">
                                </div>
                            </div>
                        </div>
                        <div >
                            <div >
                                <h4><?=$player['playerName']?></h4>
                                    <p>Buy Now Price <span ><?=$player['buyPrice']?></span></p>
                                    <p>Market Price: <span ><?=$player['marketPrice']?></span> </p>
                                    <p>Price In Dollar: <span ><?=$player['price']?></span></p>
                            </div>
                            <button type="button" ><span ><i ></i>
                                    </span>Buy</button>
                        </div>
                    </div>
                </div>
            </div>
    </div>
    <?php } } ?>
        </p>
</div>


<script>
    setInterval(function() {
        $(".parent").load(document.URL  ' #players');
    }, 1000); 
</script>

CodePudding user response:

Here's a sample code:

<script>
    $(document).ready(function(){
        setInterval(function() {
            fetchNewProducts();
        }, 1000); 
    });
    function fetchNewProducts(){
        let get = $.get('<Your URL to fetch new products>', {
            lastProdId: "<Insert_Max_Fetched_ProdId>",
        })
        get.done(response => {
            response = JSON.parse(response);
            if (!response.error) {
                $('#targetDiv').append(response.data)
            } else {
                alert(response.message);
            }
        })
    }
</script>

Note that in the PHP URL to fetch data, it should return a complete html of the products, that'll simply get appended in the already rendered list. The controller logic should be such that if no data is found, then response.data is just an empty string.

  • Related