0

I have an ajax call:

jQuery.ajax({
  type:'POST',
  url: 'http://www.mytestsite.com/wp-admin/admin-ajax.php',
  data:{
       'action':'display_image',
       'id_page': 9
       },
  success:function(data){
    $('#ajax').html(data);
  }
}); 

It works perfectly my div ID "ajax" display the html code:

<span id="test">HELLO</span>

The problem is in my footer page i have:

$('#test').on('click', function(){
alert('test');
});

When i click on "HELLO" (the html return of my ajax call) an alert box will display but it doesnt work. I dont know why...

anna33
  • 17
  • 2
  • 4

2 Answers2

2

You have to bind the clickevent after you show the resulting htmlcode on the page. So just put the on-function inside your success function.

schaffioverflow
  • 510
  • 3
  • 14
1

Because the content is loaded dynamically, you have two options:

  1. You can bind the click event to an ancestor element that isn't dynamically loaded; so that when it is clicked, it searches for your selector and then calls the function:

    $('body').on('click','#test', function(){
       alert('test');
    });
    
  2. After your content is loaded, you can bind a new event to that content. This would need to occur in your AJAX success callback (or some sort of promise). This would be a little more involved, since you said the code was in your footer page.

vol7ron
  • 40,809
  • 21
  • 119
  • 172