I am using a simple JavaScript function to call a PHP script when I click a button or link and to return some data. It works fine until I try to call data from a already outputted data via that function. Let show you my script:
$(function() {
$(".article_edit").click(function() {
var article_id = $(this).attr("id");
var dataString = 'article_id='+article_id;
//$('a#'+article_id).removeClass('liked');
$('#post-body-'+article_id).fadeOut("slow").html('<img src="images/loader.gif" class="loading" />');
$('a#'+article_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "action/article_enable_edit.php",
data: dataString,
cache: false,
success: function(data){
if (data == 0) {
alert('Actiunea nu a putut fi realizata!');
} else {
$('#post-body-'+article_id).fadeIn("slow").html(data);
}
}
});
return false;
});
});
$(function() {
$(".article_edit_close").click(function() {
var article_id = $(this).attr("id");
var dataString = 'article_id='+article_id;
//$('a#'+article_id).removeClass('liked');
$('#post-body-'+article_id).fadeOut("slow").html('<img src="images/loader.gif" class="loading" />');
$('a#'+article_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "action/article_show.php",
data: dataString,
cache: false,
success: function(data){
if (data == 0) {
alert('Actiunea nu a putut fi realizata!');
} else {
$('#post-body-'+article_id).fadeIn("slow").html(data);
}
}
});
return false;
});
});
<!-- First button-->
<a class="color-transition article_edit" href="#" id="'.$id.'"><i class="fa fa-pencil-square-o"></i></a>
<!-- When I click it the content will be replaced with another one containing this-->
<!-- output from action/article_enable_edit.php -->
<a class="color-transition article_edit_save" href="#" id="'.$id.'" ><i class="fa fa-save"></i></a>
<a class="color-transition article_edit_close" href="#" id="'.$id.'" ><i class="fa fa-ban"></i></a>
<!-- Now, if i click on any link, for example: .article_edit_close, the function will not work. -->
<!-- i should have an output from action/article_show.php -->
<!-- If I put these oow links on the index.php page, they worked, but that is not what I need.-->
Why can't I call a function from a content which is called by another function? They do not happen at the same time....
You need to bind the click
event of link/button using .on
for dynamic elements.
So your click event code will look something like this,
$('body').on('click','.article_edit_close',function(e){
// Your code goes here...
});
.on() attach an event handler function for one or more events to the selected elements.