Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh jQuery code after AJAX request

Let's say, for example, that I have some buttons that calls AJAX requests when clicked.

$(document).ready(function(){
    $('button').each( function() {
        $(this).click( function() {
                    alert('Clicked.');
            // ...AJAX request...
        });
    });
});

When I click on a button, everything works fine.

But if I load the buttons with an AJAX request and then I click on them, the code above stops working.

How can I get rid of this?

I have tried the on() method

$(document).ready(function(){
    $('button').each( function() {
        $(this).on('click', function() {
                    alert('Clicked.');
            // ...AJAX request...
        });
    });
});

But it's just the same. Works normally, doesn't work on AJAX-loaded content.

I'm stuck, please help me.

P.S.: I am using the latest version of jQuery (v1.7.1).

like image 966
Simone Avatar asked Feb 23 '23 03:02

Simone


1 Answers

You should do:

$(document).ready(function(){
       $('body').on('click','button', function() {
                    alert('Clicked.');
            // ...AJAX request...
        });
});

In this way is the body element that handles all the click event on the <button> elements and it works even if they are added through AJAX.

Instead of using the <body> tag you could use something that wraps those <button>...in any case read the docs of jQuery for on(), it's pretty straightforward.

P.S. in case you are wondering, live()works exactly as i used on(), jQuery just intercept events when they bubble up the DOM

like image 186
Nicola Peluchetti Avatar answered Mar 04 '23 00:03

Nicola Peluchetti