简体   繁体   中英

How to use ajax within another ajax in jquery?

I made a jquery code like :

$('button').click(function(event) {

});

In it; I put $.post and sent data to a php file and return table rows. In every rows, there is an 'add' button.

Then I made another jquery code for these buttons like :

$('.row_button').click(function(event) {

});  

Again, I put $.post and tried to send data about that row and wanted to fetch information via ajax request. But it didn't work. Nothing happend. I looked code and there is no error.

Isn't it possible to use ajax within another ajax? Or is there another way? Thank you.

That is because those newly injected elements don't know about the click event binding you already have.

Solution : use jquery on function.

Change

$('.row_button').click(function(event) {

});

to

$(document).on("click",".row_button'",function(event) {

});

jQuery on works for current and future elements (newly injected elements via ajax /dynamically adding new elements using javascript) . It is available from jQuery 1.7+ version. If you are using an earlier version of jQuery, consider using jquery live (As of jQuery 1.7, the .live() method is deprecated)

Try to use this instead second code:

$('.row_button').live('click',function(event) {
  ...
});  

Jquery .live attach an event handler for all elements which match the current selector, now and in the future.


Edit

.live is now deprected so use .on insted:

$(document).on("click",".row_button'",function(event) {

});

From Jquery documentation:

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM