0

I am not really sure if I have asked the question correctly.

The problem is i have Page 1 that calls Page 2 with jQuery ajax. Then Page 1 puts the returned data into a div with using .html(data). This part works perfect however when want to create a .click function to a element in loaded div code it does not perform any action. my code looks like this.

Page 1:

<div class="settings"></div>

<script>
$(document).ready(function(e){
$.ajax({
type: 'POST',
url: "Page2.php",                 
success: function(data) {
    $('.settings').html(data)
}
});

$('.links').click(function(e){
 alert("it worked");
});

});
</script>

Page 2 Code

<ul><li class="links">Test 1</li> <li class="links">Test 2</li></ul>
Shomz
  • 37,421
  • 4
  • 57
  • 85
Aslan Kaya
  • 514
  • 5
  • 11

1 Answers1

1

You need to either put the click listener function inside the AJAX callback, or use delegated listeners (using .on()):

First approach

$(document).ready(function(e){
$.ajax({
type: 'POST',
url: "Page2.php",                 
success: function(data) {
    $('.settings').html(data);
    $('.links').click(function(e){
      alert("it worked");
    });
}
});

});

Second approach (better)

$(document).ready(function(e){
$.ajax({
type: 'POST',
url: "Page2.php",                 
success: function(data) {
    $('.settings').html(data)
}
});

$('.settings').on('click', '.links', function(e){
 alert("it worked");
});

});
Shomz
  • 37,421
  • 4
  • 57
  • 85