-2

I make Ajax Request. Success evet function is a div html chance. Ajax successful but runFunction function dont run.

$("#dashboard").html("<img src='xxxxxx' class='runFunction'>");

HTML Code:

<div id="dashboard">
  <div class="Loader"><div class="ball-pulse"><div></div><div></div><div></div></div></div>
</div>

AJAX Code:

function getGuilds() {
  $.ajax({
    type: "POST",
    url: "includes/ajax/getGuilds.php",
    dataType: "json",
    success: function(respo) {
      if (respo.type == "success") {
        $("#dashboard").html("<img src='xxxxxx' class='runFunction'>");
      } else {
        getGuilds();
      }
    }
  })
}
getGuilds();

My Function:

$(".runFunction").click(function(){
  alert(1);
});
Berk
  • 3
  • 2
  • 5
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Taplar Jun 12 '18 at 18:20

1 Answers1

0

do you need to change your listener to this:

Javascript:

$(document).on("click", ".runFunction", function(){
   alert(1);
});

The problem is that at the time your run the function .runFunction the ajax has not finished or you have not created the element img with class .runFunction and does not exist, but when you change the function using the document it works even if you create the element after.

Regards!

Radames E. Hernandez
  • 3,261
  • 20
  • 29