Reputation: 917
I have a list of data or "quotes" that are being displayed, I only limited 10, but I want more to show....
<ul class="recent-list">
<?php
require("inc/connect.php");
$result = mysql_query("SELECT * FROM entries ORDER BY id DESC LIMIT 0, 20", $link);
while($row = mysql_fetch_array($result)){
?>
<li id="<?php echo $row['id']; ?>" class="quote-wrap group">
<span>
some stuff here....
</span>
<div class="quote">
<p>
<?php echo htmlentities($row['quote']); ?>
</p>
</div><!-- /.quote -->
</li>
<?php } ?>
</ul>
Then on the bottom of the list, there is a link of "Show more", where the data that is being displayed fades away and the next set of data appears.
I think I understand the "ajax" part. It'd look something like this.
$(document).delegate("'#load-more'", "click", function(){
$.post("load-more.php", $(this).serialize(), function(data) {
// success?
});
});
Where load-more.php is the file I need to create to load in more data, and run mysql queries. That part is what confusing me.
After clicking the "show more" link, how can I fetch the next set of data with PHP? I'm new to PHP and ajax so this is a hard one for me.
Upvotes: 0
Views: 2374
Reputation: 29989
OK! So first thing to do is create an external PHP file with the code for getting data from the database.
This file should have the ability to be passed a $_POST or $_GET variable with the starting index that you want to query records from. It should look something like this:
require("inc/connect.php");
$start = $_GET['start'];
$limit = $_GET['limit'];
We define the $start variable, which will hold the value of the first ID that should be returned in the query. Then the $limit variable which holds the number of rows to get from the database.
$result =
mysql_query("SELECT * FROM entries ORDER BY id DESC LIMIT $start, $limit", $link);
Then we construct and execute the query using these variables. At this stage it starts getting a little more complex.
$data = array(); //We create an empty array to store the new values in.
while($row = mysql_fetch_array($result)){//Then we loop through the return results.
//Each row variable is an object, should have two properties
// $row['id'] & $row['quote']
// So we add this object into our $data array.
array_push($data, $record);
}
//Now PHP works some of it's magic and turns that $data array into something
//that javascript can understand. A JSON string.
echo(json_encode($data));
When Javascript reads this string with it's AJAX call, it will be able to turn it back into an array of objects, which will still have the properties that the $row variable had. In Javascript though, rather than referring to properties of an object with a ['property'] or ->property syntax like PHP, we use .property.
I'm being brave here, I don't know whether you have heard much about JSON, but there is plenty of support for it on the internet if you look around. It is incredibly useful to understand. Basically we have just used PHP to create an array of objects with the properties id and quote in both. And then we echo it out as a JSON string.
So, if we go to this URL:
http://localhost/quotes.php?start=0&limit=10
Then we should see a page that looks something like this:
[
{
"id":0,
"quote":"The first quote."
},
{
"id":1,
"quote":"The second quote."
},
{
"id":2,
"quote":"The third quote."
},
...
]
Now it won't be formatted that well, but if you run it through a JSON formatter (google it). Then it should resemble something similar to that. Make sure it works before you carry on!
Then, I would remove the embedded PHP from your page, and get everything with AJAX using the PHP script that you have just written.
Next, create a jQuery function that sends an AJAX request to the PHP file. Something like:
function getQuotes(start, limit) {
//Clear the recent list element
$(".recent-list").html("");
$.ajax({
url:"http://localhost/quotes.php?start="+start+"&limit="+limit,
success: function (data) {
data = eval(data);
//Data should now be a javascript array of objects.
for(i=0;i<data.length;i++) {
$(".recent-list").append("<li id='"+data[i].id+"' class='quote-wrap-group'><li>");
$("#"+i).html("<div class='quote'><p>"+data[i].quote+"</p></div>");
}
}
});
}
I am aware that last function could look a bit confusing, an AJAX request is made to your PHP page, the data is collected and turned into an array. We loop through the array, and insert the values into the page in the same way that you had it configured earlier.
If you contain the current index in a variable called currentIndex, then you can know what index to request next. You can use this variable to decide which is the next index to pull down with something like
getQuotes(currentIndex+10, 10);
This can all be chained together with a button somewhere on the page, e.g.
<button id="more">Get more quotes</button>
Then at the top of your Javascript section:
$(document).ready(function(){
$("more").click(function(){
getQuotes(currentIndex+10, 10);
currentIndex += 10;
});
});
This creates a function so that whenever you click on the button the old results are removed from the and the new ones are added, also incrementing the currentIndex so that it stays correct.
Although this might seem like a complicated way to do it, if you learn this technique it will simplify a whole lot in terms of debugging and future projects. So it is worth sticking with this to see if you can get it working.
Another thing I would note is that if this data is sensitive then you should be using $_POST variables (jQuery supports them still), and if there is a large amount of data you should be capping the limit in the PHP file.
Finally, all of this code was written in Stack Overflow, off the top of my head so there might be something wrong. I hope you can get this sorted, and I hope this helped you!
Upvotes: 3