Jquery, Ajax save to database - php

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!

Related

Update Mysql Records Onclick Bootrstrap Checkbox Toggle

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.

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>

Ajax change icon color add/remove wishlist

Example :
If user has already added product A in wishlist heart icon should be display in red color, And If user click on add to wishlist button it will remove product A from wishlist and heart icon should be display in grey color.
<a class='addtowishlist' href='javascript:;' data-data='".$row['p_id']."'><i class='fa fa-heart'></i> Add to Wish list</a>
ajax
<script type="text/javascript">
$(document).ready(function(){
$(".addtowishlist").live('click', function(evt) {
var link_data = $(this).data('data');
$.ajax({
type: "POST",
url: 'addtowishlist.php',
data: ({product_id: link_data}),
success: function(data) {
}
});
});
});
</script>
addtowishlist.php
<?php
session_start();
include 'connect.php';
if(isset($_POST['product_id'])) {
$addmemberid = $_SESSION['member_id'];
$addproductid = $_POST['product_id'];
$result = mysql_query("SELECT count(w_p_id) cnt FROM wishlist WHERE w_m_id = '$addmemberid' AND w_p_id = '$addproductid'") or die(mysql_error());
$countid = mysql_fetch_assoc($result);
if($countid['cnt'] == 1){
mysql_query("DELETE FROM wishlist WHERE w_p_id = '$addproductid' AND w_m_id = '$addmemberid'") or die(mysql_error()); // If product has already added to wishlist then remove from Database
} else {
mysql_query("INSERT INTO wishlist SET w_p_id = '$addproductid', w_m_id = '$addmemberid'") or die(mysql_error()); // If product has not in wishlist then add to Database
}
}
?>
Add a class to your heart icon.
<i class='fa fa-heart whishstate'>
Change your addtowishlist.php to something like that:
<?php
session_start();
include 'connect.php';
if(isset($_POST['product_id'])) {
$addmemberid = $_SESSION['member_id'];
$addproductid = $_POST['product_id'];
$result = mysql_query("SELECT count(w_p_id) cnt FROM wishlist WHERE w_m_id = '$addmemberid' AND w_p_id = '$addproductid'") or die(mysql_error());
$countid = mysql_fetch_assoc($result);
if($countid['cnt'] == 1){
mysql_query("DELETE FROM wishlist WHERE w_p_id = '$addproductid' AND w_m_id = '$addmemberid'") or die(mysql_error()); // If product has already added to wishlist then remove from Database
echo '0';
} else {
mysql_query("INSERT INTO wishlist SET w_p_id = '$addproductid', w_m_id = '$addmemberid'") or die(mysql_error()); // If product has not in wishlist then add to Database
echo '1';
}
}
?>
Then in change your ajax call to something like that:
<script type="text/javascript">
$(document).ready(function(){
$(".addtowishlist").live('click', function(evt) {
var link_data = $(this).data('data');
$.ajax({
type: "POST",
url: 'addtowishlist.php',
data: ({product_id: link_data}),
success: function(data) {
if(data == '1')
{
$('a[data-data="' + link_data + '"] > i.whishstate').css({"color":"red"})
}
else{
$('a[data-data="' + link_data + '"] > i.whishstate').css({"color":"red"})
}
}
});
});
});
</script>
$(".addtowishlist").live('click', function(evt) {
Change this to
$(".addtowishlist").on('click', function(evt) {

query to fetch tables after a certain timestamp not working

I am trying to calculate the total earnings after a certain timestamp.
What I want to do:
I have a button which on click adds the total earnings till that time to the table with a timestamp.
As soon as it gets added to the database, from there on i want to display the total earnings earned after that timestamp.
So, that means if there are no earnings after the click of the button, it should show me 0.
Problems:
The thing works only the first time if the database is empty. Otherwise Values are correctly inserted in the database but the jquery doesnt update the span tags each time I hit the button.
HTML:
<span id="wb_uid8">Earned: </span><span id="wb_uid9">Fetching data..</span>
<input type="submit" id="Button1" name="Button1" value="I received my incentive today!">
<span id="wb_uid10"><strong>Last payment receive date:</strong></span><span id="wb_uid11"> </span><span id="wb_uid12"></span><span id="wb_uid13"><br>
</span><span id="wb_uid14"><strong>Received amount:</strong></span><span id="wb_uid15"> </span><span id="wb_uid16"></span>
jQuery:
<script>
$(document).ready(function()
{
$('#Button1').click(function(){
var fullDate = new Date();
var twoDigitMonth = fullDate.getMonth()+"";
if(twoDigitMonth.length==1){
twoDigitMonth="0" +twoDigitMonth;
}
var twoDigitDate = fullDate.getDate()+"";
if(twoDigitDate.length==1){
twoDigitDate="0" +twoDigitDate;
}
var currentdate = twoDigitDate+"/"+twoDigitMonth+"/"+fullDate.getFullYear();
var dataString = 'date='+currentdate;
$.ajax({
type:"POST",
data: dataString,
url: "receipts.php",
cache:false
});
return false;
});
});
</script>
<script type="text/javascript">
$(function(){
setInterval(function(){
$.ajax({
url: 'checkearnings.php',
success: function(data){
var data=JSON.parse(data);
$('#wb_uid9').html('₹ '+ data['earned']);
$('#wb_uid12').text(data['lastdate']);
$('#wb_uid16').html('₹ '+ data['lastamt']);
}
});
}, 1000);
});
</script>
checkearnings.php
<?php
include 'connect.php';
$earned = 0;
$lastdate = "";
$lastamt = "";
$timestamp = "";
$sql = "SELECT * FROM receipts ORDER BY date DESC LIMIT 1";
$result1 = mysqli_query($db, $sql);
if($details = mysqli_fetch_array($result1)){
$lastdate = $details['date'];
$lastamt = $details['amt'];
$timestamp = $details['timestamp'];
}
else{
$lastdate = "Never";
$lastamt = "Nothing";
}
$sql = "SELECT amt FROM sales WHERE timestamp>'$timestamp'";
$result = mysqli_query($db, $sql);
while($fetch_options=mysqli_fetch_array($result)){
$earned = $earned + $fetch_options['amt'];
}
$responses=array('earned'=>$earned, 'lastdate'=>$lastdate, 'lastamt'=>$lastamt);
$return=$responses;
//echo $earned;
echo json_encode($return);
?>
receipts.php
<?php
include 'connect.php';
include 'checkearnings.php';
if (isset($_POST['date']))
{
$newdate = $_POST['date'];
$time = round(microtime(true)*1000);
$sql = "INSERT `receipts` (`date`, `amt`, `timestamp`) VALUES ('$newdate', '$earned', '$time')";
$results = mysqli_query($db, $sql);
mysqli_close($db);
}
?>

how to update number without reloading

I am working on a voting system in jquery. I have it where a user can vote up or if they change their mind vote down and it deducts from the upvote and puts it in on the down vote. But my problem is I cant get both numbers to refresh when a vote is selected so it just uses the original number instead of the updated number.
Vote Page
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id=' + id;
var parent = $(this);
if (name == 'up') {
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});
</script>
<?php
$sql=mysql_query("SELECT * FROM uploads LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg=$row['title'];
$mes_id=$row['id'];
$up=$row['up'];
$down=$row['down'];
?>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?> up
</a>
<div class='down'>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="down">
<?php echo $down; ?>
</a>
</div>
<div class='box2' >
<?php echo $msg; ?>
</div>undefined</div>undefined
<?php } ?>
The up_vote.php page..
(down_vote.php is exactly the same as up_vote except it just changes up to down.)
<?php
include("config.php");
$ip = $_SERVER['REMOTE_ADDR'];
if ($_POST['id']) {
$id = $_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql = mysql_query("select ip from votes where img_id='$id' and ip='$ip'");
$count = mysql_num_rows($ip_sql);
if ($count == 0) {
// Update Vote.
$sql = "UPDATE uploads SET up=up+1 WHERE id='$id'";
mysql_query($sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into votes (id,img_id,ip,type) values ('','$id','$ip','up')";
mysql_query($sql_in);
} else {
//if already voted change it..
$result = mysql_query("SELECT * FROM votes WHERE img_id='$id' AND ip='$ip'");
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
$up = mysql_query("UPDATE uploads SET up=up+1 WHERE id='$id'");
$down = mysql_query("UPDATE uploads SET down=down-1 WHERE id='$id'");
$vote = mysql_query("UPDATE votes SET type=up WHERE img_id='$id' AND ip='$ip'");
}
}
$result = mysql_query("select up from uploads where id='$id'");
$row = mysql_fetch_array($result);
$up_value = $row['up'];
echo $up_value;
}
?>
Not an answer but too long for a comment. This script:
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
/* ... */
}
I don't think you need it like it is now. You are actually only using the last fetched row, not all of them. If that's your intention (because there's only one), then you don't need the while() at all. You could change it for:
$row = mysql_fetch_row($result);
$vote_type = $row['type'];
if ($vote_type == 'down') {
/* ... */
}
Furthermore, I'd recommend to change your code to PDO. It's more secure and mysql_* is deprecated.

Categories