Although i have followed the sample code from http://api.jquery.com/jQuery.post/ and of course Stackoverflow i couldnt find a solution to my problem.
I have a toggle image in html which everytime a user clicks on it,changes the image and update the column in the DB.Here is the code:
HTML
<input type="image" src="smileys/heart.gif" class="play" onclick="toggle(this,'<?php echo $ida;?>')"/>
AJAX
function toggle(el,al){
if(el.className=="play")
{
el.src='smileys/lol.gif';
el.className="pause";
$.post("update.php", { "hr": 1, "ida": al } );
}
else if(el.className=="pause")
{
el.src='smileys/heart.gif';
el.className="play";
$.post("update.php", { "hr": 0, "ida": al } );
}
console.log(al);
return false;
}
update.php
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$database = "db";
$heart=$_GET["hr"];
$ida=$_GET["ida"];
$con = mysql_connect($host,$user,$pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
mysql_query("UPDATE tablename SET heart='$heart' WHERE id='$ida'");
?>
The toggle function works well but the DB is not updated when a user clicks and the image. I believe it has to do with the $.post
function,not sending correctly the data to the php.
BTW if i do
http://domain.com/update.php?hr=1&ida=127
it works.
NOTE: I am using mysql and not PDO only for this example. ...and yes my code is messy and ugly,still learning. Any help? Thanks
Well, it's a _POST request and not an _GET, so, to capture its values you need to use $_POST
instead $_GET
.
Also, as i noticed, there's and _GET link, so you need to change your $.post
with $.get
.