skip to Main Content

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


  1. pass data to PHP file

    data: { id: id },
    

    add a database connection to your PHP file

    <?php
     $var = $_POST['id'] ;
     $sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = '$var'";
     $result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
    ?>
    

    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 helps

    Login or Signup to reply.
  2. From 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() line

    Change this

    onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"
    

    To

    onClick="UpdateRecord('<? echo $profile['online_status']; ?>');"
    

    Also you are hardcoding the where clause in your update statement. You should be using the $_POST['id'] variable via prepared statements

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search