Rounds
Rounds

Reputation: 1889

Ajax load more from PHP

Updated:

I want to make a load more ajax button, I want it to load data from a php file which will extract data from database.

I've managed to make it to load just once, however when I click the new more button it doesn't work.

Here's the Javascript:

$(document).ready(function(){
    $(".more").click(function(){
        var ID = $(this).attr("id");
        if(ID) {
            $("#more"+ID).html('<img src="moreajax.gif" />');

            $.ajax({
                type: "POST",
                url: "more.php",
                data: "lastimg="+ ID,
                cache: false,
                success: function(html){
                    $("div#updates").append(html);
                    $("#more"+ID).remove(); // removing old more button
                }
            });
        } else {
            $(".morebox").html('The End');// no results
        }

        return false;
    });
});

And here's more.php

$lastimg = mysql_real_escape_string($_POST['lastimg']);

$result = $mmhclass->db->query("SELECT * FROM `file_storage` WHERE `is_private` = '0' AND `file_id` < '$lastimg' ORDER BY `file_id` DESC LIMIT 10;", array(MYSQL_FILE_STORAGE_TABLE));

while($row=mysql_fetch_array($result))
{
$file_id = $row['file_id'];
$filename = $row['filename'];
?>
    <li>
        <?php echo $filename; ?>
    </li>
<?php
}
?>
<div id="more<?php echo $file_id; ?>" class="morebox">
    <a href="#" class="more" id="<?php echo $file_id; ?>">more</a>
</div>

Upvotes: 0

Views: 7956

Answers (2)

ramesh
ramesh

Reputation: 4082

I think you may use jQuery live function

$(".more").live("click", function(){ 

// Code here
});

Upvotes: 0

user1823761
user1823761

Reputation:

It just work once, because after your ajax completed, the .more element will be new on the page, so the click event handler you attach to it, isn't working anymore.

You must use event delegation:

$('body').on('click', '.more', function () {
    // your code
});
  • Note: jQuery 1.7+ required.

References:

  • .on() - jQuery API Documentation

Upvotes: 3

Related Questions