Gjert Ingar Gjersund Gjert Ingar Gjersund - 7 months ago 13
Javascript Question

Running an Ajax click event on a div added by another Ajax click event

For some reason I can't run the Ajax click on a div that was just added by another ajax click event on the exact same page.

Both ajax requests use the same request page, but contain a different data string.

These are my two Ajax functions

$(document).ready(function(){
$('#log_login').click(function(event){
event.preventDefault();
var email=$("#log_email").val();
var login=$("#log_login").html();
var dataString = 'email='+email+'&login='+login;
$.ajax({
type: 'POST',
url: '$language_rewrite/$administrator_login/forgotpassword',
data: dataString,
beforeSend: function(){
$("#login-msg").hide();
$("#log_login").html('$translate_login_8...');
},
success: function(html){
if(html){
if(html.indexOf("$forgot_translate_1") > -1){
$("#p_log_email").html('$forgot_translate_1');
$("#log_verify_code").html('<input id="log_code" type="text" name="email" placeholder="$admin_f_subject"/><br>');
$("#log_verify_btn").html('<div id="log_verify" name="login" class="standard-button">$admin_verify_btn</div>');
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
});
});
$(document).ready(function(){
$('#log_verify').click(function(event){
event.preventDefault();
var code = $("#log_code").val();
var verify = $("#log_verify").html();
var dataStringTwo = 'code='+code+'&verify='+verify;
$.ajax({
type: 'POST',
url: '$language_rewrite/$administrator_login/forgotpassword',
data: dataStringTwo,
beforeSend: function(){
$("#login-msg").hide();
$("#log_verify").html('$admin_verify_btn...');
},
success: function(html){
if(html){
if(html.indexOf("1") > -1){
$("#log-verify").html('<div id="log_login2" name="login" class="standard-button">FINISHED</div>');
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
});
});


This is the HTML code that is being changed

<div id="log_verify_code">
<input id="log_email" type="text" name="email" placeholder="<?php echo $translate_login_2; ?>"/><br>
<input id="log_code" type="hidden" value=""/>
</div>
<div id="log_verify_btn">
<div id="log_login" name="login" class="standard-button"><?php echo $translate_login_8; ?></div>
<input id="log_verify" type="hidden" value=""/>
</div>


The first Ajax functions works perfectly, and it changes the input field, however when I press the second button nothing happens. Not even an error, or a PHP error. Nothing. How come?

Answer

Event handlers are bound only to existing elements. For future elements you must use delegated events and bind to existing ancestor, or for instance the document itself.

$(document).on("click", ".future-elem", function() {
  // code here
});

Source: $.on - read: direct and delegated events

EDIT: just saw this was already being commented

Comments