I am trying to build like unlike system on PHP AJAX. I'm almost done but the way I am doing it is not correct I think.
Here is the code:
<?php $query=mysqli_query($conn,"SELECT * FROM posts");
while($data=mysqli_fetch_array($query)){
?>
<table border="1" width="50%" align="center" style="margin-top: 20px;">
<tr>
<td>
<!-- Name -->
<strong><?php echo $data["author"] ?></strong>
</td>
</tr>
<tr>
<td>
<!-- post content -->
<?php echo $data["content"]; ?>
</td>
</tr>
<tr>
<td>
<input type="hidden" value="<?php echo $data["id"]; ?>" id="like<?php echo $data["id"]; ?>">
<button type="submit" id="likebtn<?php echo $data["id"]; ?>">Like</button></td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
//displaydata();
// body...
$("#likebtn"+<?php echo $data["id"]; ?>).click(function(){
var like= $("#like"+<?php echo $data["id"]; ?>).val();
$.ajax({
url: "ajax.php",
type:"POST",
async:false,
data:{
"done":1,
"id" : like,
},
success:function(data){
//displaydata();
//$("#like").val('');
}
});
});
});
</script>
<?php } ?>
The problem is AJAX code is in the loop so if there is multiple posts the code repeats multiple times which I don't want, and if I put the AJAX code out of the loop then only the first button data is executed because the ID is same of all posts. I can create a dynamic ID for each post but how can I use dynamic ID in AJAX?
In your case you can use class for each Dynamic buttons
So your this code
<button type="submit" id="likebtn<?php echo $data["id"]; ?>">Like</button></td>
should be
<button type="submit" class="btnSubmit" id="likebtn<?php echo $data["id"]; ?>">Like</button></td>
And you can use it in ajax like this
$(".btnSubmit").click(function(){
var id = $(this).attr("id");
$.ajax({
url: "ajax.php",
type:"POST",
async:false,
data:{
"done":1,
"id" : id,
},
success:function(data){
//displaydata();
//$("#like").val('');
}
});
});
Since you are not submitting via a form, you don't need to declare a name
attribute, nor type="submit"
. You don't even need to declare an id
or a class
. You can write an onclick
event to all <button>
tags and access the dynamic data which is best/logically stored in a data-id
attribute using this
.
First build your buttons in your php loop like this:
echo "<button data-id=\"{$data['id']}\">Like</button>";
This should output html similar to this:
<button data-id="1">Like</button>
<button data-id="2">Like</button>
<button data-id="3">Like</button>
<button data-id="4">Like</button>
In your javascript, (after the page is loaded) you can write your event function like so:
$("button").on("click", function(){
$.ajax({
url: "ajax.php",
type:"POST",
async:false,
data:{
"done" : 1,
"id" : $(this).data("id")
},
...
});
});
Here is a little jsfiddle demonstration: https://jsfiddle.net/xpvt214o/20542/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.