prytsh
prytsh

Reputation: 84

Jquery inside Ajax loaded page does not work

When I use

$('body').html(data1)

or

$('html').html(data1)

in AJAX, then any HTML tag or jQuery function does not work on the loaded page.

$.ajax({
    type:"GET",
    dataType: 'html',
    url: 'hell.php',
    success : function(data1) {
        alert(data1);// will alert "ok"
        $('body').html(data1);
    },
});

Upvotes: 0

Views: 209

Answers (3)

Labu
Labu

Reputation: 2582

First, define the functionality you want to attach to the loaded elements in a function, e.g.:

function attachEventsAfterAjax(){

    $('.aLoadedElement').on('click', function(){
        console.log('Yay!');
        return false;
    });

}

Then, after you've loaded your new content, call that function, e.g.:

$.ajax({
    [...],
    success: function(data){

        // Don't replace the <body> HTML, that's not a good idea
        // $('body').html(data);

        $('#container').html(data);
        
        // Now attach the functionality!
        attachEventsAfterAjax();

    }
});

Upvotes: 0

user2768948
user2768948

Reputation:

better use jQuery live function, when attaching event handlers. See: http://api.jquery.com/live/

Upvotes: 0

Flea777
Flea777

Reputation: 1022

The events you attached before $('body').html(data1) will not fire simply because the elements previously in the body will not exist anymore.

You have to re-attach the events or use .on() method and attach events directly to document.

Upvotes: 1

Related Questions