2

I've been looking to find a way to update some data into my database when execute onclick function. The idea is to update the value of a button contains the word "Active" and when execute onclick like to update into mysql to "Inactive" This is the button:

$register_status = '<button class="btn btn-success btn_status btn-block" data-status="Active">Active</button>';

How to give the data variable so that we can fetch it in PHP using $_POST? The above representation of the data variable shows an error.

scripts.js

$(document).ready(function(){
  $('body').click('.btn_status', function(e){
  var button = jQuery(e.target);
        if(button.data('status') == 'Active'){ 

        var data = {id:id, register_status:Inactive};
        $.ajax({
           type: "POST",
           dataType: "json",
           url: "ajax/updateStatus.php",
           data: data,
           success: function(data) {
                alert("update!");
           }
        });

        }else if(button.data('status') == 'Inactive'){
          alert("nothing");
        }
  });
})

ajax/updateStatus.php

include("db_connection.php");

if(isset($_POST))
{
    $id = $_POST['id'];
    $register_status = $_POST['register_status'];
    $query = "UPDATE `users` SET `register_status` = '$register_status'  WHERE `id` = '$id'";
    if (!$result = mysqli_query($db,$query)) {
        exit(mysqli_error());
    }
}

UPDATE:

This is another function to delete. This function is run correctly.

function DeleteUser(id) {
        $.post("ajax/deleteUser.php", {
                id: id
            },
            function (data, status) {
                readRecords();
            }
        );
}

deleteUser.php

<?php
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
    include("db_connection.php");
    $user_id = $_POST['id'];
    $query = "DELETE FROM users WHERE id = '$user_id'";
    if (!$result = mysqli_query($db,$query)) {
        exit(mysqli_error());
    }
}
?>

and when do a click I can remove:

<li onclick="DeleteUser('.$row['id'].')"><a href="#">Delete</a></li>

However, this doesn't seem to work. If there's a better way to do what I mentioned above. thanks

12
  • 1
    Shouldn't Inactive be quoted, or else it's passing along an attempt of a variable? Commented Jul 3, 2019 at 16:39
  • yes. It's a variable that I want to pass at php. maybe there is another better option Commented Jul 3, 2019 at 16:42
  • Where is Inactive defined in your javascript? Also, try var_dump($_POST); to see what it contains Commented Jul 3, 2019 at 16:47
  • 1
    var data = {id:id, register_status:Inactive}; <== missing quotes on 'Inactive'? Commented Jul 3, 2019 at 16:55
  • 2
    Additionally, your script is susceptible to SQL Injection. Commented Jul 3, 2019 at 16:57

1 Answer 1

2

Based on the example, you will want to make some changes:

JavaScript

$(function(){
  function updateStatus(id, st){
    $.post("ajax/updateStatus.php", {"id": id, "register_status": st}, function(data, status){
       console.log("Update Success", data, status);
       readRecords();
    });
  }

  $('body').on('click', '.btn_status', function(e){
    var button = $(this);
    updateStatus(1001, (button.data("status") === "Active" ? "Inactive" : "Active"));
  });
});

First, using the click() as you had, was not exactly the best way to do it. Using .on() will be better as it can handle any new or dynamically created items.

This script will require id to be defined someplace. The AJAX needs to send the id info to the PHP. The code you posted does not show this, so I am not sure what it's value should be.

PHP (updateStatus.php)

include("db_connection.php");

if(isset($_POST['id'])){
    $id = (int)$_POST['id'];
    $register_status = ($_POST['register_status'] == "Inactive" ? "Inactive" : "Active");
    $query = "UPDATE `users` SET `register_status` = '$register_status'  WHERE `id` = '$id'";
    if (!$result = mysqli_query($db,$query)) {
        exit(mysqli_error());
    }
}

These updates can help prevent SQL Injection. I would advise using Prepared Statements to further prevent it.

Update

If you're button is going to be something like this:

<button onclick="ChangeStatus('.$row['id'].') class="btn btn-success btn_status btn-block" data-status="Active">Active</button>

Notice that this is only passing in just the ID from PHP. If these items will always be "Active", then yes, you can do this with something like:

function ChangeStatus(id){
  $.post("ajax/updateStatus.php", {id: id}, function(data, status){ console.log(status, data)});
}

With PHP like:

<?php
if(isset($_POST['id']) && $_POST['id'] != ""){
  include("db_connection.php");
  $user_id = (INT)$_POST['id'];
  $query = "UPDATE `users` SET `register_status` = 'Inactive'  WHERE `id` = '$user_id'";
  if (!$result = mysqli_query($db,$query)) {
    exit(mysqli_error());
  }
}
?>

Hope this helps.

Sign up to request clarification or add additional context in comments.

6 Comments

I update the post with another function that it's run. I put the jquery code but not update the value on database
@GuifIf I have updated my answer. You still need to pass an ID and Status in to the new function. It's based on your other example.
I update the initial question. I add how to remove a value with the funcidion DeleteUser. Think that the id variable can pass correctly. How would the code be?
@GuifIf you will notice there that when the link is created, it's passed an ID from PHP: $row['id'] and that is passed into DeleteUser() that is bound to click callback. You'lll need to do something similar.
but inside (for example a function called ChangeStatus) can do this? <button onclick="ChangeStatus('.$row['id'].') class="btn btn-success btn_status btn-block" data-status="Active">Active</button>or how can pass the $row[id] inside the button?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.