The question is fairly simple. Whenever user clicks on “like” I want to use javascript to update the mysql database through ajax. I have tried all means bit have found nothing helpful. I know I will also need a server side script but the ajax is the main issue.
Here is the counter code I set up.
document.observe("dom:loaded", function()
{
$("likeForumLink").onclick=processForumLike;
});
function processForumLike(event)
{
var numberOfLikes=parseInt($("hiddenLikes").value);
numberOfLikes+=1;
$("hiddenLikes").value=numberOfLikes+"";
this.innerHTML="You liked this";
if(numberOfLikes==1)
{
$("numberOfLikes").innerHTML="("+numberOfLikes+" like)";
}
else
{
$("numberOfLikes").innerHTML="("+numberOfLikes+" likes)";
}
var likes=$("hiddenLikes").value;
new Ajax.Request("seeForum.php?id=$("subjectId").value", {
method:'get',
parameters:{hiddenLikes:likes},
onSuccess: ???? //Don't know
onComplete:??? //Don't know
on Failure:???? //Don't know
});
}
And then I can use my server side script as follows.
P.S. It lies in the same page "seeForum.php?subjectId=$("subjectId").value"
<?php if(isset($_GET["hiddenLikes"]))
{
$updateQuery="UPDATE `subject table` SET `likes`='".$_GET["hiddenLikes"]."' where `subjectId`='".$_REQUEST['subjectId']."' ";
$result=mysql_query($updateQuery);
checkConnect($result,"query of $updateQuery");
?>
Please help. All my work has come to a halt.
First of all, you shouldn’t be using a GET request to update data, that should be a POST. And this:
doesn’t do what you probably think it does. What it does do is cause a syntax error because it looks like
"x" x "x"to the JavaScript interpreter and that’s not JavaScript. I’m not sure which JavaScript library you’re using (Prototype perhaps?) but I think you probably want to put all your parameters intoparametersto avoid having to worry about URL encoding and things like. Furthermore, there’s no reason to tell the server how many “likes” you already have and there is a good reason not to: someone might have “liked” the page while you’re looking at some the number of likes you currently have will be wrong; sohiddenLikesisn’t needed at all.Something like this would be better on the JavaScript side:
And then, in the PHP, just send a simple UPDATE to the database to increment the number of likes in
likeIt.php, something like this: