Denn
Denn

Reputation: 83

Ajax including a page

Can I make some functions on a loaded page from Ajax? I.E.

$(function() {
    $.ajax({
        url: "loaded.php",
        success: function(data) {
            $("#content").html(data);
        }
    });
    $("a#edit").click(function(e) {
        e.preventDefault();
        var newVal = $(this).closest("tr").find("#collapse").html();
        $(this).html(newVal);
    });
});

Both a#edit and #collapse are elements of the loaded.php and this code is in the index.php page... Will this code work?

Upvotes: 1

Views: 100

Answers (2)

Musa
Musa

Reputation: 97717

You have two options attaching the handler in the success function after you add the html to #content or use delegation.

Option 1

    success: function(data) {
        $("#content").html(data);
        $("#edit").click(function(e) {
            e.preventDefault();
           var newVal = $(this).closest("tr").find("#collapse").html();
           $(this).html(newVal);
        });
    }

option 2

$(function() {
    $.ajax({
        url: "loaded.php",
        success: function(data) {
            $("#content").html(data);
        }
    });
    $("#content").on('click', '#edit', function(e) {
        e.preventDefault();
        var newVal = $(this).closest("tr").find("#collapse").html();
        $(this).html(newVal);
    });
});

http://api.jquery.com/on/

Upvotes: 2

sgrif
sgrif

Reputation: 3822

If your $("a#edit") element is something returned by your ajax, then no this code will not work. You need to move that block of code into the success callback.

$(function() {
    $.ajax({
        url: "loaded.php",
        success: function(data) {
            $("#content").html(data);
            $("a#edit").click(function(e) {
                e.preventDefault();
                var newVal = $(this).closest("tr").find("#collapse").html();
                $(this).html(newVal);
            });
        }
    });
});

Upvotes: 0

Related Questions