Update MySQL if checkbox Unchecked - php

I am using the script found here to update my database if a box is checked.
https://stackoverflow.com/posts/4592766/revisions
It works if I check an unchecked box.
However, I can't seem to get it working if I uncheck a checked box. It will not update the database.
Here is the modified code:
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var isSel = this.checked;
var isNotSel = this.unchecked; //added
$.ajax({
url: 'file.php',
type: 'POST',
dataType: 'json',
data: {
id : this.id,
isSelected : isSel,
isNotSelected : isNotSel // added
},
success: function(data) {
alert('updated');
},
error: function() {
alert('error');
}
});
});
});
This is the code showing the checkboxes (created from database):
if($status == 'pending')
{ echo '<input type="checkbox" name="status" id='.$submission_id.' >' .
$task_name . '<br>'; }
if($status == 'done')
{ echo '<input type="checkbox" name="status" id='.$submission_id.' checked>'
. $task_name . '<br>'; }
Here is the code for file.php
if ($_POST && isset($_POST['isSelected'])) {
$sql = 'UPDATE ft_form_53 SET status = "done" WHERE submission_id = ' . $_POST['id'];
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
if ($_POST && isset($_POST['isNotSelected'])) {
$sql = 'UPDATE ft_form_53 SET status = "pending" WHERE submission_id = ' . $_POST['id'];
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
No error message is thrown. Any ideas?

Change
var isNotSel = this.unchecked;
to
var isNotSel = !isSel;
or
var isNotSel = !this.checked;
Checkboxes don't have an unchecked property. They have a boolean checked property (true if checked, false if not). And you've already grabbed that into isSel, so...

Got it working. Thanks to shehary for the click to change modification and to T.J. Crowder for the !this.checked tip. I ended up using two separate scripts but it works :) Thanks again to all!
The one below is for uncheck.
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var isNotSel = !this.checked;
$.ajax({
url: 'file.php',
type: 'POST',
dataType: 'json',
data: {
id : this.id,
isNotSelected : isNotSel
},
success: function(data) {
alert('updated');
},
error: function() {
alert('error');
}
});
});
});

Related

Sweet alert in ajax and php content not working

I'm trying to get a value from my database and then run an update using sweet alert pop-up but it is not working. The alert seem to pop-up and once the value is entered, it displays the value entered but not working. below is my actual ajax code:
viewproduct.php
<script>
$(document).ready(function() {
$('.btnupdatestock').click(function() {
var id = $(this).attr("id");
//var new_stock = $(this).val();
swal("Add Stock:", {
content: "input",
})
.then((updateStock) => {
$.ajax({
type: 'POST',
url: 'stock-in.php',
data:{
stock_up: updateStock,
},
success: function(data){
swal(`Updated: ${updateStock}`);
},
error: function(data){
swal(`Error updating: ${updateStock}`);
}
});
});
});
});
</script>
the above method was designed to trigger sql in stock-in.php and the code in stock-in.php is below:
<?php
include_once'connectdb.php';
if($_SESSION['useremail']=="" OR $_SESSION['role']=="Admin"){
header('location:index.php');
}
$idd=$_GET['id'];
$select=$pdo->prepare("select * from tbl_product where pid=$idd");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ)){
$productName = $row['pname'];
$oldstock = $row['pstock'];
//$id=$_POST['uid'];
$stockup=$_POST['stock_up'];
alert('I clicked');
$new_stock = $oldstock + $stockup;
$sql="UPDATE `tbl_product` SET `pstock` = ? WHERE pid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$new_stock, $idd]);
if($result){
echo'Stock updated!';
}else{
echo'Error in updating stock';
}
}
?>
below is a picture of my UI that shows pop-up but it's not updating.
This is what I intend to do: If a user clicks on update and enters a value say 50, it should retrieve the old stock (database, say 100) and add to the new stock (value entered, say 50) and then update the database with 150. I am stuck here and any help would be appreciated. Thanks.
$(document).ready(function() {
$('.btnupdatestock').click(function() {
swal("Add Stock:", {
buttons: true,
closeModal: true,
content: "input",
}).then((updateStock) => {
if (updateStock === "") {
swal("You need to write something!");
return false
}else{
$.ajax({
type: 'POST',
url: 'stock-in.php',
data:{
stock_up: updateStock
<?php
echo ', id: '.$row->pid.' '
?>
<?php
echo ', oldstock: '.$row->pstock.' '
?>
},
success: function(data){swal(`Updated: ${updateStock}`);},
error: function(data){swal(`Error updating: ${updateStock}`);}
});
}
});
});
});
The major issue I had was I didn't make the SQL query global at the top of my page and then applied '.$row->pid.'

Delete by AJAX request

I have a button which call this AJAX request to delete record.
How could I show/handle mysql errors correctly like:
Error: Table 'supplier_contacts' doesn't exist
// DELETE
$('.delete-btn').click(function () {
// Confirm
if (!confirm('Are you sure want to delete this row?')) {
return false;
}
// id need to delete
var contact_id = $(this).attr('contact_id');
// Current button
var obj = this;
// Delete by ajax request
$.ajax({
type: "post",
dataType: "text",
url: 'suppliers_sql.inc.php?a=delete_contact',
data: {
contact_id: contact_id
},
success: function (result) {
$(obj).parent().parent().remove();
window.location.assign('suppliers_details.php?id=<? echo $supplier_id ?>&m=success');
}
});
});
SQL QUERY of suppliers_sql.inc.php ? a = delete_contact
// --------------------------------------------------------------------------------------------
// DELETE CONTACT
// --------------------------------------------------------------------------------------------
if ($_REQUEST['a'] == "delete_contact") {
$contact_id = $_POST['contact_id'];
$sql_contact = "DELETE FROM supplier_contacts WHERE contact_id = $contact_id";
if (mysqli_query($mysqli, $sql_contact)) {
mysqli_close($mysqli);
//header("Location: suppliers_details.php?id=$supplier_id&m=success");
exit;
} else {
echo "Error: " .$sql_contact. "<br>" .mysqli_error($mysqli);
mysqli_close($mysqli);
exit;
}
}
As you are echoing something if there is an error you can display it in your success.
$.ajax({
type : "post",
dataType : "text",
url : 'suppliers_sql.inc.php?a=delete_contact',
data : {
contact_id : contact_id
},
success : function(result){
if(result)
{
//Your error
alert(result);
}
else
{
//all good
$(obj).parent().parent().remove();
window.location.assign('suppliers_details.php?id=<? echo $supplier_id ?>&m=success');
}
}
});

do not work properly duplicate entry validation in php using jquery

I have create multiple forms, this form hide and show after change a drop down value
I wank to check duplicate entry on click on submit button
than add this code
but this code do not work properly
jQuery('#form_1').on('submit', function(event) {
jQuery.ajax({
url: SITE_URL+'/admin/ajax/function.php',
type: "POST",
data: jQuery('#form_1').serialize(),
dataType : 'json',
a sync : false,
success: function(response){
if(response.status === true){
var error = '<div class="alert alert-danger">this record already exist</div>';
jQuery('.form1ErrorMsg').html(error);
return false;
}else{
alert('test');
//return true;
}
},
error: function(){
return false;
}
});
//return false;
});
function.php
if(isset($_POST['ActionToCall'])){
$Action = $_POST['ActionToCall'];
switch($Action){
default:{
break;
}
case 'chkDuplicatChiefInvigilator':{
require_once('../../class/staff.class.php');
require_once('../../class/user.class.php');
$staff = new staffmanager();
$users = new usermanager();
$result=$staff->getDuplicatChiefInvigilator($_POST);
if(!empty($result)){
$output['status']=1;
}else{
$output['status']=0;
}
print json_encode($output,true);
die;
}
}
Look at your syntax error:
dataType : 'json',
async : false,

Combining two dropdown selection to retrive one result ajax/php

I got two dropdowns and i need to get both values to get data from my database.
$(document).ready(function(){
$('.fabric').on('change',function(){
var fabricID = $(this).val();
console.log("fabric id_price is " + fabricID); //debugging
if(fabricID){
$.ajax({
type:'GET',
url:'cart_functions.php',
dataType: 'json',
data: {
fabric_id: fabricID
},
success:function(html){
$('.icms' + id).text(data.val);
}
});
//closing tags
$('.size').on('change',function(){
var sizeID = $(this).val();
if(sizeID){
$.ajax({
type:'GET',
url:'cart_functions.php',
dataType: 'json',
data:{
size_id: sizeID
},
success:function(html){
$('.icms' + id).text(data.val);
}
});
//closing tags
i'm sending these both values to my calculate.php
<?php header('Content-Type: application/json');
include_once '../incluedes/conn_cms.php';
if(isset($_GET["size_id"],$_GET["fabric_id"])){
$size_id=$_GET["size_id"] ;
$fabric_id=$_GET["fabric_id"] ;
$query3 =" SELECT * FROM valores_almofadas
WHERE size='$size_id'
AND price_id ='$fabric_id'";
$result = mysqli_query($conn,$query3);
while($rows = mysqli_fetch_assoc($result)){
if($_SESSION['estado'] == 'SP'){
$ICMS = $rows['icms_7'];
}else{
$ICMS = $rows['icms_12'];
}
$_SESSION['icms']=$ICMS;
} echo json_encode($_SESSION['icms']);
}
?>
So i select a fabric and then a size fabric value is my id and size is 50 or 45.
fabricid= 1 and size = 50 <-- i am sending this to my calculate.php
So i want to get back the value into a session.
and the result must be on a td..
<td class="icms'.$id.'">R$:'.$_SESSION['icms'] .'</td>
But its not working, i'm not good at ajax, can you tell me whats wrong and how can i fix these mess?
Make sure both values are always sent with the request
$(document).ready(function() {
$('.fabric, .size').on('change', sendData);
function sendData() {
var fabricID = $('.fabric').val();
var sizeID = $('.size').val();
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'cart_functions.php',
dataType : 'json',
data : {
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(html) {
$('.icms' + this.id).text(data.val);
});
}
}
});
You are never sending both values in any ajax call, only one or the other. You need to additionally get the value for fabric_id in your .size change event and vice versa.

Can't Get AJAX Success Message To Work

Racking my brains for hours with this. I have the following PHP AJAX script:
<script type="text/javascript">
$(document).ready(function(){
$("#submitValue").click( function(){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
type: "POST",
url:"acctUpdate.php",
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
dataType: "dataString",
success: function(data){
$('#results').html('Success').delay(1000).fadeOut();
}
});
});
});
</script>
I am trying to get the message 'Success' to populate this span element;
<span id="results"></span>
But just can't seem to get it to work.
The PHP is as follows (the table is updated just fine);
if($_POST['acctDB'] == 'profile') {
$uemail = $DB->real_escape_string($_POST['uemail']);
$uage = $DB->real_escape_string($_POST['uage']);
$city = $DB->real_escape_string($_POST['city']);
$urname = $DB->real_escape_string($_POST['urname']);
$uname = $DB->real_escape_string($_POST['uname']);
$uID = $DB->real_escape_string($_POST['uID']);
mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
}
Anyone be of assistance please?
dataType: "dataString"
Please comment this part and it will work.
if($_POST['acctDB'] == 'profile') {
$uemail = $DB->real_escape_string($_POST['uemail']);
$uage = $DB->real_escape_string($_POST['uage']);
$city = $DB->real_escape_string($_POST['city']);
$urname = $DB->real_escape_string($_POST['urname']);
$uname = $DB->real_escape_string($_POST['uname']);
$uID = $DB->real_escape_string($_POST['uID']);
mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
echo 'yes';
}
// add echo 'yes'; at php submit page.
change the script as follows
$.ajax({
type: "POST",
url:"acctUpdate.php",
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
// dataType: "dataString",
dataType : "text",
success: function(data){
$('#results').html(data).delay(1000).fadeOut();
return false;
}
});
return false;
In php file change this
$qry = mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
if($qry)
echo "Success";
}
When you make an ajax call and you pass the values to a php file, you will also need to return the response.
So at the end of your query if everything is completed successful you will do something like this:
return Response::json(array(
'success' => true,
'message' => trans('admin.update_success'),
), 200);
And your ajax cal looks something like this:
$("#submitValue").click(function(e){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
url: 'acctUpdate.php',
type: 'POST',
dataType: 'json',
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
dataType: "dataString",
})
.done(function(response) {
alert(response.message)
})
.fail(function(response) {
if (response.status == 400) {
var output = '<ul>';
var errors = $.parseJSON(response.responseText).errors;
$.each(errors, function(id, message) {
output += '<li>' + message[0] + '</li>'
});
output += '</ul>'
alert(output)
} else {
alert('UnknownError');
}
})
e.preventDefault();
})
So to recap:
You make the ajax call
The php file will process the data
You pass the response back to the 'done function)
And hier you can make anything you want with your response.
I have just as example inserted an alert message
Hope this helps.
Sorry but the code I have provider for you is for a Laravel framework and I suppose you are not using it. So you don't have the 'Respone::' class.
In the php file:
//if the query has success
$return = array();
$return['responseCode'] = 1;
$return['responseHTML'] = 'Success'
echo json_encode( $return );
And the ajax call:
$("#submitValue").click(function(e){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
url: 'acctUpdate.php',
type: 'POST',
dataType: 'json',
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
})
.done(function(response) {
if( response.responseCode == 0 ) {
//alert(respomse.responseHTML)
$('#results').html(response.responseHTML);
} else if( response.responseCode == 1 ) {
//alert(res.responseHTML)
$('#results').html(response.responseHTML);
}
})
e.preventDefault();
})
So I don't use the response anymore but I will just return an array with the response.

Categories