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
var_dump($_POST);to see what it containsvar data = {id:id, register_status:Inactive};<== missing quotes on 'Inactive'?