hi guys i try to create like button with php and ajax so write this codes but just work in first loop
<?php header('Cache-Control: no-cache'); ?>
<script>
$(document).ready(
function(){
$("#like").click(function(){
$.ajax({
type: "POST",
url: "<?php echo ADDRESS ;?>thank.php",
data: "like="+$("#like").val(),
success: function(result){
$("#result").html(result);
}
});
});
}
);
</script>
<?php
foreach ($this->value['posts'] as $post){
echo $post[1] . $post[0] .$post[2] . $post[3] . '</br>';
echo '<div id="result"></div>';
}
?>
I think the problem is in my #like that repeat and jquery dont know which one is our div
ok some one answered my question but id dont know why deleted :O
any way he or she writed
$(this)
thanks!
your code not worked but help me to fix that ok problem was in my button value ! all the buttons returned value for the first loop so i changed the js code to this
<script>
$(document).ready(
function(){
$(".like").click(function(){
var spdiv = ".result" + $(this).val();
$.ajax({
type: "POST",
url: "<?php echo ADDRESS ;?>thank.php",
data: "like="+$(this).val(),
success: function(result){
$(spdiv).html(result);
}
});
});
}
);
</script>
and i use class instead of id .
IDs are Identifiers - meaning they must be unique! Also your script is messy and I guess you didn't mention there are many like buttons on the page, right?
Try this PHP code:
foreach ($this->value['posts'] as $index=>$post) {
echo '<div class="comments">';
echo $post[1] . $post[0] .$post[2] . $post[3] . '</br>';
echo '<button class="like" data-id="<?php echo $index; ?>">LIKE</button>';
echo '<div class="result"></div>';
echo '</div>';
}
And this javascript:
$(document).ready(function(e) {
$("div.comments").on("click", "button.like", function(e) {
$.ajax({
type: "post",
url: "<?php echo ADDRESS ;?>thank.php",
data: {
like: $(this).attr("data-id")
},
success: function(data, textStatus, jqXHR) {
$(this).siblings(".result").html(data);
}
});
});
The script above will add an event listener to all buttons
that have the class like
. The $(this)
will refer to the like button and the $(this).siblings(".result")
will get the result div that is a direct sibling of the like button(!), meaning they both sit in the same <div class="comments">
. I have changed the way you approach DOM elements. I also added a new identifier to your LIKE button so don't forget to change this data-id
to suit your needs!