This is my first ajax attempt. I want to pass id variable to ajax function and update my database. When I run this code everything looks fine. Id in alert is correct but my database is not updated. Please tell me what is wrong with my code.
My api.php:
<?php
include 'config.php';
$page_id =$_POST['page_id'];
$result = mysql_query("SELECT State FROM alarm WHERE ID_Alarm = $page_id ");
if($result==Off){
$result = mysql_query("UPDATE alarm SET State = On WHERE ID_Alarm = $page_id");
}else{
$result = mysql_query("UPDATE alarm SET State = Off WHERE ID_Alarm = $page_id");
}
?>
My js function with ajax:
function changeImage(e) {
$.ajax({
type: "POST",
url: "web/api.php",
data:"page_id="+e.id,
success: function(data)
{
alert(e.id);
}, error: function()
{
alert("something went wrong");
}
});
}
html:
<div id=\"$i\" class=\"alarmon\" onclick=\"changeImage(this)\"> </div>
I would update your PHP file as follows:
UPDATE: Try enclosing On and Off in single quotes
<?php
include 'config.php';
$page_id =$_POST['page_id'];
$result = mysql_query("SELECT State FROM alarm WHERE ID_Alarm = $page_id ");
$state = mysql_result($result, 0);
if($state == "Off"){
$result = mysql_query("UPDATE alarm SET State = 'On' WHERE ID_Alarm = $page_id");
}
else{
$result = mysql_query("UPDATE alarm SET State = 'Off' WHERE ID_Alarm = $page_id");
}
?>
The first error I saw is that Off
was not a constant, so it has to be enclosed in double or single quotes.
Also $result will be a resource not a string.
I hope this helps.
You don't need a SELECT
and IF
. You can update the table in one query:
mysql_query("UPDATE alarm
SET State = IF(State = 'On', 'Off', 'On')
WHERE ID_Alarm = $page_id");
Enclose the $page_id in single quote like this '$page_id'. Your Code will be as follow
$result = mysql_query("UPDATE alarm SET State = On WHERE ID_Alarm = '$page_id'");
now run the code Id will be save to database.