I'm trying to create a like button for different images posted by user. This is my html :
<a href="#" title="like" class="likes" id="<?php echo $row['id']?>">Like</a>
This is my javascript:
<script>
$(function(){
$(".likes").click(function(){
var postid = $(this).attr("id");
alert(postid);
$.ajax({
type:'POST',
url:'likes.php',
data:'id='+postid,
success:function(data){
alert("success");
}
});
});
});
</script>
This is likes.php, for testing purpose it's quite simple:
<?php
require('config.php');
$postid=$_POST['id'];
echo $postid;
?>
When I clicked the like button, a small window will correctly postid, and then "success",which indicates that the ajax is successful, however, when I opened likes.php, I got an error that says: Notice: Undefined index: id in C:\XAMPP\htdocs\likes.php on line 3
I tried adding e.preventDefault(). I tried different syntax,such as data:'id='+postid, data:{id:postid},data:{'id':postid},etc. I experimented with basically all combinations of single quotes and double quotes. I also tried adding datatype:html and datatype:text. Every time I just got a alert that says "success", but when I open likes.php, $_POST['id'] is always undefined.
Can someone help me please this bug took me a lot of time.
Update: I found that even if I entered a completely non-existing url, like url:"aabbll.php", after I clicked the "like" button, I would still see a window that alerts "success", why does the page keep alerting "success" even though clearly the AJAX process wasn't a success?
You are not sending the post variable "id" when you are opening like.php in a new browser window.
The error "Notice: Undefined index" is shown because the $_POST array does not contain the id field.
You can use a chrome extension called postman to test endpoints with post variables.
A tip to improve the code could be to wrap it in an if isset statement
if(isset($_POST['id'])){
// this code will only be executed if the post variable is sent to the page
$postid=$_POST['id'];
// update database
echo "Success";
}else{
echo "ERROR: No id post variable found";
}
Your javascript code is sending the post variable
Try to put var_dump($_POST)
to see what you really post.
Couple of suggestions.
Your JS can be simply
<script>
$(function() {
$('.likes').on('click', function() {
var postid = $(this).attr('id');
$.post("likes.php", {id: postid}).done(function( data ) {
alert( 'Data Loaded: ' + data );
});
});
});
For your PHP
<?php
if (!isset($_POST['id'])) {
/// Do what you want to do in this case.
}
$id = $_POST['id'];
// If using PHP7
$id = $_POST['id'] ?? null;
Though $('.likes')
works try to avoid that since it is slowest selector in most cases.