Search code examples
jqueryajaxgetlive

jquery select after get() insertion


I'm inserting rows into a table via a get() call to a php page, which works. I then want to update the row numbers of the table.

Jquery updates all the rows except the most recently inserted one.

$("#insert_row").click(function () {
    $.get("print_row.php", function(data){
        $("#table").append(data);
    });
});

$("#insert_row").on("click", function () {
    var rowNumber = 1;
        $(".rowNumColumn").each(function () {
            $(this).text(rowNumber);
            rowNumber++;
        })    
});

I've browsed the site for a while looking for an answer to this, and the solution appears to be the live() or on() modifiers. However I can't get that to work for me.


Solution

  • You need to do the renumbering in the callback of the get. As it is now, you are renumbering prior to the get request returning. get is simply a shortcut for making an ajax get request. AJAX is asynchronous so it does not wait for the request to return before moving on.

    $("#insert_row").click(function () {
        $.get("print_row.php", function(data){
            $("#table").append(data);
    
            var rowNumber = 1;
            $(".rowNumColumn").each(function () {
                $(this).text(rowNumber);
                rowNumber++;
            }) 
        });
    });