I am trying to load more data from a database with a jQuery .load
, and it works perfectly, but after the first load, it ist'n bringing more data.
Also, for bringing the first content, which is brought on the first page load, i use a PHP foreach()
loop, like this as a basic example:
<div class="grid-products">
<?php foreach($products as $product): ?>
<div class="grid-product">
<?php echo $product['name']; ?>
</div>
<?php endforeach; ?>
</div>
I am trying to load more data from my database on scroll, so the user don't have to click on a button. I am loading information from my database based on the method of this question, like this:
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
//do an ajax call
}
});
But as I don't know how to do the ajax call mentioned on the answer above I found, I decided to use a jquery .load
passing also some POST
method variables, which in this case would be productNewCount
. First I set its value to 6, and when user reaches bottom of page, we sum plus six to its value, like this:
$(window).scroll(function() {
var productCount = 6;
if($(window).scrollTop() == $(document).height() - $(window).height()) {
productCount = productCount + 6;
$(".grid-products").load("load-products.php", {
productNewCount: productCount
});
}
});
This works great on first load, and so when this is executed, it loads on the <div class="grid-products">
the load-products.php
file. Here, the variable $connection
is calling my function to connect to the database, don't give too much importance to it.
This is load-products.php
:
<?php
$connection = connect();
$product_new_count = $_POST['productNewCount'];
$sentence = $connection->prepare("
SELECT * FROM all_products ORDER BY date DESC LIMIT $product_new_count
");
$sentence->execute();
$products = $sentence;
?>
<?php foreach($products as $product): ?>
<div class="grid-product">
<?php echo $product['name']; ?>
</div>
<?php endforeach; ?>
In the sentence, we are calling to bring all the rows from the all_products
table ordered through its date
column, and limiting to bring only the rows product_new_count
says, which its value is the productCount
JS variable we brought on the main file, before its load.
I made sure there are still rows available to bring, so the reason why other rows arent being shown after first load isn't because there are no rows left. Also, terminal isnt showing any errors or warnings and there is also still available space to make scroll so the function can be called.
Can I bring more data through this .load
method or should I use the AJAX call mentioned on the answer I found? If so how?