0

I've got a few functions in JQuery that stop working after I perform an Ajax request (to a PHP file) to add elements to the DOM.

This is the ajax function:

function paginacion(pagina){
  $.ajax({
    method: "GET",
    url: "paginacion.php",
    data: {pag: pagina}
  })
    .done(function(msg) {
    $(".bt_container").remove();
    $(".contenido").append(msg);
  });
}

Here I call it:

$(".button").on("click", function(){

  var pag = parseInt($(this).attr("data-pag"));
  pag++;

  paginacion(pag);

});

When I click the button, it works correctly the first time. But the elements I retrieve, should work with another function, and they don't, while the previous elements do work without any problem. Also, the old button gets removed and another one gets added at the end of the file, being retrieved by the same function as above. That button doesn't work either.

I'm sure that I'm having some problem with JQuery, making it to not work with these new DOM element's I'm retrieving. What can I do to make it work?

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Zerok
  • 1,323
  • 1
  • 24
  • 56

4 Answers4

3

Use event delegation:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).on('click', '.button', function () {
    var pag = parseInt($(this).data("pag"));
    //                         ^^^^
    pag++;
    paginacion(pag);
});

Also, use data() to get data attribute value.

http://api.jquery.com/data/

Refer: http://learn.jquery.com/events/event-delegation/

Tushar
  • 85,780
  • 21
  • 159
  • 179
2

It is loaded dynamically! Use .on for Event Delegation.

$("body").on('click', '.button', function () {
    var pag = parseInt($(this).attr("data-pag"));
    pag++;
    paginacion(pag);
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
2

You need to use .on() for bindig events for dynamically generated elements

$(document).on('click', '.button', function () {
    var pag = parseInt($(this).attr("data-pag"));
    pag++;
    paginacion(pag);
});
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

You are looking for Event delegation. You dynamically added and replace the dom elements use event delegation.

$(".contenido").on("click", ".button", function(){
//------^ Immediate parent or document
    // Your code
});
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49