Update jQuery code after AJAX request

Say, for example, that I have buttons that trigger AJAX requests when clicked.

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

When I press the button, everything works fine.

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

How can I get rid of this?

I tried the on() method

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

But still. It works fine, does not work with loaded AJAX content.

I'm stuck, please help me.

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

+4
source share
5 answers

You should:

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

So this is a body element that handles all click events in <button> , and works even if they are added via AJAX.

Instead of using the <body> you can use something that wraps those <button> ... anyway, read the jQuery docs for on () , it's pretty simple.

PS in case you're interested, live() works just like I used on() , jQuery just hooks events when they bubble DOM

+8
source

You must install click handlers after the buttons are already on the page. If you do this while loading the page, then the buttons loaded by ajax are not yet ready to accept the assignment of a handler.

0
source

try on .

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

and one loop will be enough, there is no need for each loop, because the on loop itself detects all button elements and fires the click event.

0
source

Probably the safest (and least error prone) approach is to bind click events AFTER you have loaded the buttons using AJAX.

0
source

I prefer the delegate in this matter.

 $(document).ready(function(){ $('body').delegate('button','click',function(){ alert('Clicked.'); }); }); 

Working example: http://jsfiddle.net/MarkSchultheiss/cKVGb/

some background discussion of the delegate, live and bind: http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery

And finally, the .on () documentation so you can use this: http://api.jquery.com/on/

so that you are ALMOST correct! first existing buttons:

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

now new (and old)

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

Source: https://habr.com/ru/post/1386113/


All Articles