I have a MYSQL Table called users.
I also have a column called online_status.
On my page I want a user to be able to toggle their status as ‘Online’ or ‘Offline’ and have this updated in the database when they click on the div using Ajax, without refreshing the page.
Here’s my PHP/HTML code:
<?php if ($profile['online_status'] == "Online") {
$status = "Offline";
}else{
$status = "Online";
} ?>
<div id="one"><li class="far fa-circle" onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"/></li><? echo 'Show as ' .$status; ?></div>
My Ajax:
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "update_status.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
update_status.php
<?php
$var = @$_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = 1";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//added for testing
echo 'var = '.$var;
?>
I am currently getting no alert, nothing is being updated in my database either. Please can someone help me improve/fix the code to get it to work? Also, if there’s a way of eradicating the need for the update_status.php file and have the ajax self post then this would be preferred.
Thank you in advance.
2
Answers
pass data to PHP file
add a database connection to your PHP file
If you still see any errors then press
F12
and go to network tab, then click on that div, network tab will record your ajax file returns, you can check there on by selecting your php file’s response, hope it helpsFrom what i see, the reason why no alert pops up nor nothing gets updated is because of the
onclick()
on button you have. Add quotes around the parameter to the update function. As you have it, javascript sees the parameter as a javascript variable as$profile['online_status'];
is a string.If you had debugged your code, you should see an error pointing towards the
onclick()
lineChange this
To
Also you are hardcoding the where clause in your update statement. You should be using the
$_POST['id']
variable via prepared statements