I am retrieving data from a mysql database, 5 items each time.
$query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5");
$query->execute([$_POST["id"]]);
while($row = $query -> fetch()) {
echo "<div id="$row["id"].">".$row["name"]."</div>";
});
The following javascript is retrieving data from/via the above mysql query. I am passing through the last id of each div and the sql is just taking ones with smaller/older ids to append them below.
function request(id) {
var data1 = "id=" + id;
$.ajax({
type: "POST",
url: "https://example.com/api",
data: data1,
cache: false,
success: function(html) {
$(".div").append(html);
},
error: function(XHR){
}
});
};
request();
$(document).on("click",".more",function(){
var id = $(".div").children( ":last" ).attr("id");
request(id);
});
Is there a clean way to flag the last result within the php loop so i can pick it up with javascript/jquery and hide the load ".more" button?
You can apply next steps:
names table and store it in hidden input$query = $pdo->prepare("SELECT COUNT(*) C FROM names");
...
<input type="hidden" value="<?= $row['C'] ?>" id="table_rows_count" />
hidden input for counter value<input type="hidden" value="0" id="counter" />
hidden div container and store new items in it<div style="display:none;" id="hidden_div"></div>
length of children in the hidden containerupdate counter valuecompare count of rows and children length and if they are equal then hide the .more button...
success: function(html) {
$(".div").append(html);
$("#hidden_div").append(html);
var len = $("#hidden_div")[0].children.length,
coun = $('#counter').val(),
new_counter = coun + len,
table_rows = $('#table_rows_count').val();
$('#counter').val(new_counter);
if (table_rows == new_counter) $('.more').css('display','none');
$("#hidden_div").html('')
},
...
Note: the output of your $.ajax() request has to be present only as a list of divs tags (<div>...</div>), nothing else.
Also, you've forgot to pass an argument into your first-call function request().