Update Mysql Records Onclick Bootrstrap Checkbox Toggle - php

I want to edit status field for selected column onclick of bootstrap checkbox toggle.....Please Help
Example :
1. if status is active then when user click then it should be update in database as inactive and reload page.
2. if status is inactive then when user click then it should be update in database as active and reload page.
Fetch Database
<?php
require_once 'db_config.php';
$output = array('data' => array());
// do not fetch status 3 because it is deleted
$sql = "SELECT *,emailnotificationstable.id as sid FROM notificationslist";
$query = $connect->query($sql);
$num_rows = mysqli_num_rows($query);
$x = $num_rows;
while ($row = $query->fetch_assoc()) {
// activate button
$activateButton = '';
if ($row['status'] == 1) {
$activateButton =
'<input type="checkbox" id="toggleBtn" name="toggleBtn" checked data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
} elseif ($row['status'] == 2) {
$activateButton =
'<input type="checkbox" id="toggleBtn" name="toggleBtn" data-toggle="toggle" data-on="Active" data-off="Inactive" data-onstyle="success" data-offstyle="danger" data-size="mini" value="'.$row['sid'].'" onclick="editMember()">';
}
// extra code here
$output['data'][] = array(
$x,
$activateButton,
$row['date'],
$row['notificationname'],
$row['employeename'],
$createdby,
$editedby,
$editeddate,
$deleteButton,
);
$x--;
}
// database connection close
$connect->close();
echo json_encode($output);
Jquery
// global the manage memeber table
var mytable;
$(document).ready(function() {
mytable = $("#mytable").DataTable({
"ajax": "../pages/php_action/salesexe/retriveemailnotifications.php",
"order": [],
"fnDrawCallback": function() {
jQuery('#mytable #adBtn').bootstrapToggle();
}
});
});
function editMember(sid = null) {
if(sid) {
// remove the error
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
// empty the message div
$(".edit-messages").html("");
// remove the id
$("#membersid").remove();
// click on toggle button
$("#adBtn").click(function() {
$.ajax({
url: 'notifstatus.php',
type: 'post',
data: {membersid : sid},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
mytable.ajax.reload(null, false);
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
}
}
});
}); // click toggle btn
} else {
alert('Error: Refresh the page again');
}
}
Update
<?php
require_once 'db_config.php';
$output = array('success' => false, 'messages' => array());
$membersId = $_POST['membersid'];
// update record to inactive
$sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = $membersId";
$query = $connect->query($sql);
if($query === TRUE) {
$output['success'] = true;
$output['messages'] = 'Notification trigger successfullt activated for selected user';
} else {
$output['success'] = false;
$output['messages'] = 'Error while activating notification trigger for selected user,';
}
// close database connection
$connect->close();
echo json_encode($output);

You're thinking way to complex with reloading a page, not using the API as you should. You only want to fetch the status and update the needed parts this means you need a proper way to identify a row in your table. Also an html id must be unique in a page better remove that.
You have a couple of options:
use datatables ajax requests so it can handle multiple edits on different cols.
toggle the button on and off using jquery and bootstrap.
Shown below is the latter:
$(function() {
// hooking event only on buttons, can do tr's as well.
$('.toggleBtn').click(function(){
$.ajax({
url: 'notifstatus.php',
type: 'post',
data: {
id : $(this).val(),
status: $(this).prop('checked')
},
dataType: 'json',
success: function(response){
if(response.success){
$(this).bootstrapToggle('enable');
console.log(response.message);
} else {
$(this).bootstrapToggle('disable');
BootstrapDialog.show({
title: 'failed to update status',
message: response.status + response.messages
});
}
},
error: function(xhr, textStatus, errorThrown) {
BootstrapDialog.show({
title: textStatus,
message: errorThrown
});
}
});
});
});
Now the only response to build is the following:
<?php
require_once 'db_config.php';
if(isset($_POST['status']) && $_POST['status']){
// user requests to turn off
$sql = "UPDATE notificationslist SET notfistatus = '2' WHERE id = ?"; // SQL injection, use prepared statements. fix it.
} else {
// user requests to turn on, other query.
}
$success;
$status = 0;
$message = 'Error while activating notification trigger for selected user,';
if($query = $connect->query($sql)){
if($row = $query->fetch_assoc()){
$success = true;
$message = 'Notification trigger successfully activated for selected user';
$status = $row['status'];
}
}
die(json_encode([
'success' => $success,
'messages' => $message,
'status' => $status
]));
?>
Should do the trick, no need to request all data to update a single value.

Related

PHP - Make a submit button send info to database

Hello I am new at coding and I have a question I hope some of you guys with some experience can help me with.
I have a page with some text and a button "Confirm". When this button is clicked by me, I first want to redirect to "loading.php" and in the mysql database I want to recieve "confirmed" or "ok" anything like that. Then in my dashboard I want to manually press "Next" on the unique-userid to redirect to "page3.php"
I would need some help with this and a simple "template" on how the button would be programmed in my php.
Script in my PHP where I have the button.
$(document).ready(function() {
var allInputs = $(":input");
$('#SubmitConfirm').submit(function(e) {
e.preventDefault();
var confirm = $('#confirm').val();
if (confirm == null) {
return false;
} else {
}
$.ajax({
type: 'POST',
url: 'files/action.php?type=confirm',
data: $('#confirm').serialize(),
success: function(data) {
console.log(data);
var parsed_data = JSON.parse(data);
if (parsed_data.status == 'ok') {
//console.log(parsed_data);
location.href = "Loading.php"
} else {
return false;
}
//console.log(parsed_data.status);
}
})
});
});
And here is "confirm" in action.php
if($_GET['type'] == 'confirm'){
if($_POST['confirm'] == true){
$submit = $_POST['confirm'];
$uniqueid = $_POST['userid']; // unique userid
$query = mysqli_query($conn, "UPDATE customers SET confirm='$confirm', status=1, buzzed=0 WHERE uniqueid=$uniqueid");
if($query){
echo json_encode(array(
'status' => 'ok'
));
}else{
echo json_encode(array(
'status' => 'notok'
));
}
}
}
}
I have tried but I only got 404 error when I pressed the button
from dashboard.
$query = mysqli_query($conn, "SELECT * from customers");
if($query){
if(mysqli_num_rows($query) >= 1){
$array = mysqli_fetch_all($query,MYSQLI_ASSOC);
//print_r($array);
}
}
foreach($array as $value){
$user = $value['user'];
$confirm = $value['submit'];
$info = "
uniqueID : $user
Confirm: $confirm
echo "

How to change a value in onclick function button

i will like to change the status of a user in my database from inactive to active by clicking on a button.
i have a function already which show if the use is active or inactive on the database by asigning a value to them eg 0 for inactive and 1 for active.
below is the function that change the value on the button if the user is inactive or active
if ( $row["active"] == 1 ) {
echo '<button class="btn-u btn-u-green" type="button">Active</button>';
} else {
echo '<button class="btn-u btn-u-red" type="button">Inactive</button>';
}
now i need to create a function that handle the active and inactive button. like when an admin clicks on inactive (Button) it update the value into the database to 1 (Active), and if the admin click on the active button again it update the value to 0 (inactive),
below is what i have done so far
Button Table bellow
<td>
<?php
if ( $row["active"] == 1 ) {
echo '<button onclick="button" name="active" class="btn-u btn-green" type="button">Active</button>';
} else {
echo '<button name="inactive" class="btn-u btn-u-red" type="button">Inactive</button>';
}
?></td>
database settings
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "testone";
try
{
$conn = new PDO ("mysql:host=$hostname;dbname=$databasename",$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["active"]))
}
$query = "INSERT INTO users(active) VALUE (:1)";
$statement = $conn->prepare($query);
$statement->execute(
array(
'users' => $_POST['active']
)
);
$count = $statement->rowCount();
if($count > 0)
{
echo "data insert successfully";
}
else
{
echo "data insertion failed";
}
}
}
catch(PODExeption $error)
{
echo $error->GetMessage();
}
?>
function i used
<script
src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous">
</script>
<script>
$(document).raedy(function(){
$('button[type="button"]').click(function(){
var active = $(this).val();
$.ajax({
url:"activateagent.php",
method:"POST",
data:{users:active},
success: function(data){
$('$result').html(data);
}
});
});
});
</script>
in my console i get this error ReferenceError: button is not defined
Thanks
There are so many errors in the code, make following changes:
<td>
<?php
if ( $row["active"] == 1 ) {
echo '<button class="btn-u btn-green btn_send" id="<?php echo $row["active"];?>">Active</button>';
} else {
echo '<button class="btn-u btn-u-red btn_send" id="<?php echo $row["active"];?>">Inactive</button>';
}
?></td>
Now in JQuery code make these changes:
$(document).ready(function(){
$('.btn_send').on('click',function(){
var active = $(this).attr('id');
$.ajax({
url:"activateagent.php",
method:"POST",
data:{users:active},
success: function(data){
$('$result').html(data);
}
});
});
});

Jquery, Ajax save to database

I am trying to create a simple attendance register for a kids club, when they turn up for a practice session they need to record who's paid on the night. It's more or less works as I want it to, but I'm struggling with the last bit.
When I click on the button to add a user_id to the paid table, along with the date and and status, it does as expected, so all good there. However, I would like the button to change icons based on Paid status, which I can do buy reading a database value -
<button type="button" class="btn btn-sm btn-success btn-status" id="<?php echo $row['user_id']; ?>" data-status="<?php echo $row['status']; ?>" title="Active/Deactive details" >
<?php if(empty($row['status'])){ ?>
<i class="fa fa-thumbs-up" aria-hidden="true"></i>
<?php }else{ ?>
<i class="fa fa-ban" aria-hidden="true"></i>
<?php } ?>
On button click the following jQuery handles the post event -
$(document).on('click', '.btn-status', function(ev){
ev.preventDefault();
var btn_button = $(this);
var status = 1;
btn_button.html(' <i class="fa fa fa-spinner fa-spin"></i> ');
var tbl_id = $(this).attr("id");
var tbl_status = $(this).data("status");
if(tbl_status == 0) status = 1;
else status = 0;
$.post('save_details.php', { form_name: "user_status", tbl_id: tbl_id, status: status }, function(data,status){
console.log(data);
if(data == "1"){
$('.warning-modal-message').html("Record status changed successfully.");
$('#warningModal').modal('show');
setTimeout(function(){ location.reload(); }, 2000);
}
else{
$('.warning-modal-message').html("Data deletion failed.");
}
});
});
And the PHP for the database -
if($form_name == "user_status"){
$tbl_id = mysql_real_escape_string($_POST['tbl_id']);
$status = mysql_real_escape_string($_POST['status']);
$query = "insert into attendance(rider_id, at_status, at_date) values('$tbl_id','$status',NOW())";
$result = mysql_query($query) or die(mysql_error());
if($result)
echo "1";
else
echo "0";
}
The problem I'm having is the the query relies on the status field in the user data table to control which icon is visible. What I need is a way to have all the icons set to fa-ban icon on page reload and the thumb icon when the button is pressed to take attendance.
I have tries setting the $row['status']; to 1 manually, I have tried Bootstrap Toggle Switch, Bootstrap Toggle Button and loads of articles on here but I'm not having any luck
I managed to get it working more or less as needed using Bootstrap Toggle Switch -
<input type="checkbox" id="<?php echo $row['user_id']; ?>" class="toggleBtn" name="toggleBtn" data-toggle="toggle" data-on="Paid Fees" data-off="Unpaid" data-onstyle="success" data-offstyle="danger" data-size="small" >
Using the following jQuery -
$(document).on('change', '.toggleBtn', function(ev){
ev.preventDefault();
// Disable switch on click to help prevent multiple submit
$(this).bootstrapToggle('disable');
//var btn_button = $(this);
var status = $(this).prop('checked');
//btn_button.html(' <i class="fa fa fa-spinner fa-spin"></i> ');
var tbl_id = $(this).attr("id");
var tbl_status = $(this).data("status");
//if(tbl_status == 0) status = 1;
//else status = 0;
$.post('save_details.php', { form_name: "user_status", tbl_id: tbl_id, status: status }, function(data,status){
console.log(data);
if(status == "checked"){
$('.warning-modal-message').html("Record status changed successfully.");
$('#warningModal').modal('show');
setTimeout(function(){ location.reload(); }, 2000);
}
else{
$('.warning-modal-message').html("Data deletion failed.");
}
});
});
And the following PHP -
if($form_name == "user_status"){
$tbl_id = mysql_real_escape_string($_POST['tbl_id']);
$status = mysql_real_escape_string($_POST['status']);
//SELECT * FROM `attendance` WHERE `rider_id` = 1 AND `at_date` = DATE(NOW())
$result = "SELECT * FROM `attendance` WHERE `rider_id` = '$tbl_id' AND `at_date` = DATE(NOW())";
$total = ($result);
if($total==0){
$query = "insert into attendance(rider_id, at_status, at_date) values('$tbl_id','$status',NOW())";
$result = mysql_query($query) or die(mysql_error());
}
//$query = "insert into attendance(rider_id, at_status, at_date) values('$tbl_id','$status',NOW())";
//$result = mysql_query($query) or die(mysql_error());
//if($result)
//echo "1";
//else
//echo "0";
}
A couple of the issues I'm having now is that the warnings are not showing up and the $qry to check if a rider has already been entered on the day (the switches are reset on page refresh!
if(status == "checked"){
$('.warning-modal-message').html("Record status changed successfully.");
$('#warningModal').modal('show');
setTimeout(function(){ location.reload(); }, 2000);
}
else{
$('.warning-modal-message').html("Data deletion failed.");
}
Thanks!

jquery - hold the changed text by onclick method on page reload is not working

I'm working on add to favourite functionality of my website,every thing is working fine.
When i click add to favourites button ajax call is inserting that data in db and changing the button text to 'remove from favourites'
Now problem is when i reload the page ,it again reset the text of button to 'add to favourites' which was previously marked as favourite.
My code is
<button class='btn btn-sm btn-info favourite_feature' value="<?php echo $id;?>">add to favourite</button>
JQUERY
$(".favourite_feature").click(function(){
var _this = $(this);
var postid = _this.val();
$.ajax({
type : 'POST',
url : 'add_to_favourite.php',
dataType : 'json',
data : {course_id : postid},
success : function(response){
console.log(response);
if(response.error_type == 'no error'){
alert('done');
(_this).html(_this.html()=='add to favourite' ? 'remove from favourites' : 'add to favourite');
}else{
if(response.error_type == 'login'){
$('#myModal').modal('show');
}
}
}
});
});
EDIT:ADDED SERVER SIDE CODE
<?php
session_start();
include 'includes/dbconfig.php';
if(!isset($_SESSION['google_data'])){
$response = array('success' => 0, 'error_type' => 'login');
echo json_encode($response);
}else{
$id = $_SESSION['id'];
$c_id = $_POST['course_id'];
$_SESSION['course_id']=$c_id;
$u_email = $_SESSION['google_data']['email'];
$check_favourites = "SELECT * from favourites_table where user_id = '$id' and course_id = '$c_id'";
$check_favourites_query = mysqli_query($conn,$check_favourites) or die(mysqli_error($conn));
$check_favourites_result = mysqli_fetch_array($check_favourites_query);
if($check_favourites_result){
$del = "DELETE FROM favourites_table where user_id = '$id' and course_id = '$c_id'";
$del_favourites = mysqli_query($conn,$del) or die(mysqli_error($conn));
}else{
$insert_query = "INSERT INTO favourites_table(course_id,user_id,user_email) VALUES('$c_id','$id','$u_email')";
mysqli_query($conn,$insert_query);
}
$response = array('success' => 1, 'error_type' => 'no error');
echo json_encode($response);
}
?>
On the server-side you need to check whether the item is currently added to favourites or not before you render the button, and set the text appropriately.
I don't know your data structure but let's say in PHP you can define a boolean variable $isFavourite, based on the database field where this is stored against the item in question (presumably the same item defined by $id in the snippet you've given).
So all you'd have to do is change the markup to:
<button class='btn btn-sm btn-info favourite_feature' value="<?php echo $id;?>"><?php echo ($isFavourite == true ? 'remove from favourites' : 'add to favourites')?></button>

Submit form without refresh (ajax , php)

I am trying to submit a form without refreshing the page and I want an alert message to appear when the button id=fav in clicked. this is the code but I don't know what i did wrong. Should it be on button click or on form submit?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#f1").submit(function(){
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "bookpage.php",
data: {'fav':'fav'} ,
cache: false,
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
return false;
});
});
</script>
<form action="#read" method="post" id="f1">
<div class="r1">
<button class="down" name="download" title="Add to favorites">Download</button>
<li><a class="full" href="full.php?id=<?php echo $id; ?>">Full page</a>
</li>
<button class="d-later" name="dlater">Download later</button>
<button class="fav-button" type="submit" id="fav"></button>
</div>
</form>
PHP
if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== true){
$query = "DELETE FROM favorites WHERE bid='$ii' AND email='$u'";
$result = mysql_query($query);
if(! $result ) {
die('Could not delete data: ' . mysql_error());
} $response['message'] = 'My message';
echo json_encode($response);
}else if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== false){
$query = "INSERT INTO favorites (email,book, bid) VALUES('$u','$bname','$ii')";
$result = mysql_query($query);
if(! $result ) {
die('Could not enter data: ' . mysql_error());
}
$response['message'] = 'My message';
echo json_encode($response);
}
function fav_exists($u , $ii){
$query = "SELECT id FROM favorites WHERE email='$u' AND bid='$ii'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count >= 1) {
return true;
} else {
return false;
}
}
I think you are passing empty data, see example below how to pass some data; If you want to run ajax+php you need to pass some data
<?php if(isset($_POST['action'] && $_POST['action'] == 'my_action') {
// do stuff;
// to send json response use json_encode;
$response['message'] = 'My message';
echo json_encode($response);
}
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : 'my_action' },
success: function(response){
if(response.message){
alert(response.message);
}
}
});
Also i highly recommend using PHP PDO to make SQL queries - http://php.net/manual/en/book.pdo.php
upd:
$('#fav').click(function(){
do_ajax_request('you can pass different type of acitons as param');
});
function do_ajax_request(action) {
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : action },
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
And at your php file you can switch or if/else different functions depending on your action;
<?php if(isset($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'favorites':
$msg = 'favorites action called';
breake;
case 'not fav':
$msg = 'not fav called';
breake;
default:
$msg = 'Nothing passed';
breake;
}
$Response['msg'] = $msg;
echo json_encode($Response);
}
This is what i use for the same task.
HTML
<form action="" method="post">
name:<input type="text" name="user" /> <br/>
<p><input type="submit" /></p>
</form>
JS
$(function() {
$('form').submit(function(e) {
e.preventDefault(); // Stop normal submission
data = $('form').serializeArray();
alert(JSON.stringify(data));
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'inc/update.php',
data: {
json: JSON.stringify(data)
},
dataType: 'json'
}
});
});
return false;
});
PHP
$str_json = file_get_contents('php://input');
$str_json = urldecode($str_json);
$str_json = str_replace('json=[', '', $str_json);
$str_json = str_replace(']', '', $str_json);
$arr_json = json_decode($str_json, true);
$name = $arr_json['name'];
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password);
$update = $pdo->prepare("UPDATE user SET name='".$name."' WHERE id='3';");
$update->execute();

Categories