Usually we use $.ajax or $.post to use ajax in our script. But now we are gonna use load() to send ajax requests to server.
var offset = 0;
$("#button").click(function(){
offset = offset+5;
$("#morePosts").load("/post.php?offset="+offset, function(data) {
if($(data).is(':empty')){
$(data).hide().appendTo('#morePosts').fadeIn("slow");
}else{
$("#button").attr({"disabled":"disabled", "value":"No more posts to display"});
}
});
return false;
});
I've used this in wordpress to load more posts in ajax. It'll display 5 posts each time when we click #button.
In the first parameter we are giving URL with offset as parameter to post.php(GET request).
Second parameter is the callback function used to get the data from the post.php after processing GET request.
data is the returned data from post.php and we are checking whether the data is empty or not
using is(':empty') and appending that data to #morePosts div.
Then we are using appendTo() where we first hide the data and appending it to #morePosts div and then showing it by fadeIn()
If the data is empty we disable the button attribute using attr({"disabled":"disabled"}).
Thats it!
No comments:
Post a Comment