Jump to content

Recommended Posts

I want to display 5 items and when the user clicks the 'load more' button, 5 more items will be pulled out from the database.

 

I have my items being retrieved like so:

 



    $res = mysql_query("SELECT * FROM `posts` ORDER BY `id` DESC LIMIT 5") or die(mysql_error());


if(mysql_num_rows($res) > 0){
while($row = mysql_fetch_assoc($res)){
$id = $row['id'];
$user_id = $row['user_id'];


 

 

then i have the ajax code and the button:

 



    <script type="text/javascript">
        $(document).ready(function(){
            $(".load_more").click(function (){
                $('.load_more').html('<img src="images/ajax-loader.gif" />');
                $.ajax({
                    url: "loadmore.php?lastid=" + ("<?php echo $id; ?>"),
                    success: function(html){
                        if(html){
                            $(".main_page").append(html);
                            $('.load_more').html('Load More');
                        }else{
                            $('.load_more').replaceWith('<center>No more posts to show.</center>');
                        }
                    }
                });
            });
        });
    </script>


 

 

 



<button class="load_more">Load More</button>


 

And finally the loadmore.php file that is being called when the button is clicked:

 

  


  $res17 = mysql_query("SELECT * FROM `posts` WHERE id < '".addslashes($_GET['lastid'])."' LIMIT 0, 25 LIMIT 10"); 
while($row17 = mysql_fetch_assoc($res17)){
$id = $row17['id'];
$user_id = $row17['user_id'];

 

how do i call the correct id? i know that

  url: "loadmore.php?lastid=" + ("<?php echo $id; ?>"), is probably wrong but not sure how to fix it

Make your AJAX return not just HTML but JSON that includes the HTML. Also include in that JSON the latest ID returned. It'll look something like

{"latest":123,"html":"whatever it returns now"}
Track that "latest" ID somewhere and stick the "html" into the main_page. When they click the Load More button again you can stick that ID in the URL you request.

Remember to set the default value of that latest ID with the very same <?php echo $id; ?> thing you were considering using (though it'll be in a slightly different place).

 

Word of advice: don't use the ID to sort items. Use an actual date field. Then make sure you update all the stuff to not use an ID but the latest date value instead. (Pretty much the exact same code, just using a different column for the value.)

Oh, and addslashes() is not safe. Use mysql_real_escape_string. Even better would be to stop using the mysql extension and its mysql_* functions and to switch to PDO or mysqli instead.

I will switch to date instead of id when i have more posts and i am done testing.. right now i am trying many things so the date gets messed up from time to time.

 

when you say {"latest":123,"html":"whatever it returns now"}, how exactly should i do it? and the id is from $_GET['id'] so it takes it from the url

loadmore.php is returning HTML - probably just by outputting it like normal. Instead you can use output buffering to capture the HTML, stick it into an array, put the latest ID/date in the array as well, then output the JSON-encoded array. A minimal example would be

ob_start();
// whatever you to do generate the HTML
$html = ob_end_clean();

$array = array(
    "id" => $latest_id_from_the_query,
    "html" => $html
);

header("Content-Type: application/json");
echo json_encode($array);
Now for the Javascript.

 

var latest_id_from_the_ajax = <?php echo $id; ?>;
That happens either globally or directly inside the ready(...) function; further inside the code won't work as it gets executed repeatedly later and you'll just end up overwriting whatever value you got dynamically with the $id.

url: "loadmore.php?lastid=" + latest_id_from_the_ajax,
success: function(data){
	if(data){
		latest_id_from_the_ajax = data.id;
		$(".main_page").append(data.html);
		$('.load_more').html('Load More');
	}else{
		$('.load_more').replaceWith('<center>No more posts to show.</center>');
	}
}
The "html" variable there previously wasn't representing just HTML anymore but an object (with the values you had in your array in the PHP).

 

[edit] Don't call it "latest_id_from_the_ajax", of course. Pick a better name than that ;)

Edited by requinix
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.