In my project, I use PHP to query the database(in my case, SELECT) and use while loop to fetch each row, and use it to echo back to ajax.
Like in my PHP:
$sql = "SELECT * FROM tasks A WHERE A.open = '1'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch()){
echo $row["orderDetails"];
}
In my HTML:
<script>
$(function(){
$.ajax({
method: "POST",
url: "getDetails.php",
success: function(backData){
$("#details").html(backData);
}
});
<script>
Let's say I query the database for the open tasks in my task table where task.open=1, then inside of each open task, I echo back to my ajax about these tasks details, and my ajax will change the html of the div about the task details.
So basically, the number of the open tasks, aka the number of the while loops, is the number of the echos. What is the best way to grab this number so I can show in the html how many tasks are listed here?
PS: I tried to catch this number by adding a while loop counter inside of the while loop, and add this number to an attribute of the div and echo back to ajax, however, I don't know why this echo will not take place in my end.
Thanks guys!
I solved it by adding a div with a class attribute to the echo to contain this order details and then back to my html I used jQuery to count the div with that specific class and get the number. I get the hint from here: count div elements with the same id JQUERY But you are very welcome to post a better solution for this :D
What you want to do is send back a proper JSON response, then you can just use the length property to check how many items there are. You don't need a loop to do this, just use PDO's fetchAll method. Since you are only selecting a single column, you can get it as an array of strings.
<?php
$sql = "SELECT orderDetails FROM tasks WHERE open=1";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
header("Content-Type: application/json");
echo json_encode($array);
Now you have an array of strings, you can do what you want with it, including getting its length.
<script>
$(function(){
$.ajax({
method: "POST",
url: "getDetails.php",
success: function(backData) {
// now you can work with backData as an object
var count = backData.length;
$("#details").append("<div>You have " + count + " results.</div>");
for (var i = 0; i < count; i++) {
$("#details").append("<div>" + backData[i] + "</div>"
}
}
});
});
<script>
Also note you were missing a closing }) pair in your JavaScript code.