ajax call keeps failing despite success on server site - javascript

I'm having some trouble with an ajax call.
When it's a success in one part, it's failing in the return.
Basically I have a PHP function to delete one ID in database.
The ajax call call the function and the PHP code deletes that row in table, but ajax call keeps faling. If I try to delete it again (the ID doesn't exist anymore), the ajax call shows as success with proper json to work.
function DeleteRole(e, id, role) {
Swal.fire({
title: 'Are you sure?',
text: "Do you want to delete Role " + role + "?",
icon: 'question',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
showLoaderOnConfirm: true,
confirmButtonClass: 'btn btn-primary',
buttonsStyling: false,
showCancelButton: true,
cancelButtonClass: "btn btn-danger ml-1",
preConfirm: function () {
$.ajax({
url: 'caller.php',
data: {
dados: JSON.stringify(id),
caller: 'DeleteRole',
dataType: 'json'
},
type: 'POST',
})
.done(function (response) {
console.log("done");
console.log(response);
})
.fail(function (response) {
console.log("fail");
console.log(response);
})
},
allowOutsideClick: function () {
!Swal.isLoading()
}
})
};
PHP Function:
function DeleteRole($mysqli){
header('Content-Type: application/json; charset=UTF-8');
$response = array();
$response["status"] = "error";
$response["message"] = "";
if(isset($_POST['dados'])){
$args["id"] = validate($mysqli, $_POST["dados"]);
if($stmt = $mysqli->prepare("SELECT * FROM roles WHERE id = ? LIMIT 1")){
$stmt->bind_param("i", $args["id"]);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
if ($stmt_result->num_rows>0) {
$row_data = $stmt_result->fetch_assoc();
$role_name = $row_data['role_name'];
if(crud_delete($mysqli, 'roles', $args) == true){
$response["status"] = "success";
$response["message"] = "Role ".$role_name." deleted with success";
echo json_encode($response);
}else{
$response["status"] = "error";
$response["message"] = "There was a problem deleting role ".$role_name;
echo json_encode($response);
}
}else{
$response["message"] = "ID does not exists.";
echo json_encode($response);
}
}else{
$response["message"] = "Something wrong happened.";
echo json_encode($response);
}
}else{
$response["message"] = "No data given to work.";
echo json_encode($response);
}
}
So, when I first call the function for first time do delete a specific ID, it deletes from database and should ouptut:
$response["status"] = "success";
$response["message"] = "Role ".$role_name." deleted with success";
echo json_encode($response);
Instead of that, it goes to fail part of my ajax call. Any clues?
EDIT:
First time to delete, I have an answer this way and appears in .fail of ajax call:
Array
(
[0] => id
)
{"status":"success","message":"Role Administrator deleted with success"}
If I do it a second time (the ID was already deleted first time) I have the following response (and goes to .done of ajax request):
{"status":"error","message":"ID does not exists."}

Related

Won't insert in mysql database because of script

I have a script that asks if I'm sure to add new data. My php is okay because when I want to insert data with my script disabled it inserts normally. But when my script is not disabled it will not insert anymore... I don't know why i don't get any errors (probably because there are 2 different files).
My Script
$(document).on("click", ".btnAddSubcat", function(e) {
event.preventDefault();
var subcatid = $('.CatEdit-select').val();
var subcatvalue = $('.subCat').val();
var subcatprocedure = $('.subProcedure').val();
var url = "../service/functions/postActions.php";
swal({
title: 'Add a new sub-category?',
text: "Are you sure to Add this sub-category?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Add it!'
}).then(function () {
$.ajax({
type: 'POST',
url : url,
data: {
'cat-select': subcatid,
'subCat': subcatvalue,
'Procedure': subcatprocedure
},
success: function (data) {
swal({
title: 'Add!',
text: "You Add a sub-category!",
type: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
}).then(function () {
window.location.reload();
})
}
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
if you need my php insert function or something else let me know
EDIT
My PHP function
function AddSubCat() {
$Catid = $_POST['cat-select'];
$Subnaam = $_POST['subCat'];
$procedure = $_POST['Procedure'];
include '../../../include/dbConnection/dbcon.php';
//set update query ready for database, with info from the Ajax POST method for update.
$sqladdSubCat = 'INSERT INTO `*****`(`naam`,`Werkwijze`) VALUES ("'.$Subnaam.'","'.$procedure.'")';
//if query is done right then 'Record updated successfully'
if (mysqli_query($conn, $sqladdSubCat))
{
//get new colourId
$newUpload_id = mysqli_insert_id($conn);
//set update query hw_algoritmes thee cat id that may have change.
$sqlalgotime = 'INSERT INTO `*****`(`categorie_id`, `subcategorie_id`) VALUES ("'.$Catid.'","'.$newUpload_id.'")';
//if query is done right then 'Record updated successfully'
if (mysqli_query($conn, $sqlalgotime)) {
//check if there is a new front image add
if ($_FILES['HWVideo']['name'] == "") {
//Empty
} else {
uploadVideoHw($_FILES['HWVideo'], $newUpload_id);
}
} else {
echo "Error updating record: " . mysqli_error($conn);
}
header('Location: /cms/service/index.php');
} else {
echo "Error updating record: " . mysqli_error($conn);
// header('Location:../../Categorieen');
}
}

data submit even when cancel button is pressed in sweetalert2

I was able to send data when the confirm button pressed.
however, when the cancel button pressed sweetalert2 shows as it successfully inserted the data.
back-end shows as it a empty string.(in the database table)
how to validate when I pressed the cancel button, not to send data to the back-end.
Javascript function
function inputPass(complaintID) { // complaint id pass is ok.
swal({
text: 'Input comment message',
input: 'textarea',
showCancelButton: true,
}).then(function(sample_text) {
console.log(sample_text);
if(sample_text === '') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);
$.ajax({
type: "POST",
url: "../ajax/ajax_active_deact.php?type=complaint_answered",
data: {complaintID: complaintID, sampleText: sample_text}
}).done(function (res) {
if(!res) {
swal({
type: 'error',
html: 'insert the valid text'
});
} else {
swal({
title: 'done',
text: 'all right',
type: 'success',
allowOutsideClick: false,
confirmButtonText: 'Ok'
});
}
});
}
});
}
php ajax code
function complaint_answered() {
include_once('../backend/ConsumerComplaint.php');
$con_complaint = new ConsumerComplaint();
$res = $con_complaint>mark_as_answered($_POST['complaintID'],$_POST['sampleText']);
echo $res;
}
This is my class function
function mark_as_answered($id, $comment) {
//var_dump($comment);
$val = $comment['value']; // $comment is a associative array, with the key of 'value'
$sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val'
WHERE complaint_id = '$id' ";
$res = $this->conn->query($sql);
return $res;
}
image of when i pressed cancel button in network panel in chrome
image of the console
image of the post data in chrome
I'm new to development and can't get around how to solve this issue.
please can anyone give me what I'm doing wrong here.
Thnks!
You only get the result.value if the user clicked on Ok so you can check if there is a value and if it is empty you show your error message. If there is no value nothing happens.
Snippet:
swal({
text: 'Input comment message',
input: 'textarea',
showCancelButton: true,
}).then(function(result) {
if(result.value) {
$.ajax({
type: "POST",
url: "../ajax/ajax_active_deact.php?type=complaint_answered",
data: {complaintID: complaintID, sampleText: result.value}
}).done(function (res) {
if(!res) {
swal({
type: 'error',
html: 'insert the valid text'
});
} else {
swal({
title: 'done',
text: 'all right',
type: 'success',
allowOutsideClick: false,
confirmButtonText: 'Ok'
});
}
});
} else if (result.value === "") {
swal({
type: 'warning',
html: 'cannot proceed without input'
});
}
});
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#7.28.7/dist/sweetalert2.all.min.js"></script>
Your Class:
In your php ajax code you are passing the $_POST['sampleText'] which is not an array but a string so $comment['value'] will not contain the text.
function mark_as_answered($id, $comment) {
//var_dump($comment);
$val = $comment;
$sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val'
WHERE complaint_id = '$id' ";
$res = $this->conn->query($sql);
return $res;
}
PS: Please educate yourself on SQL-Injection so people cant inject harmful code into your SQL-Queries.
Looks like sample text is always set to an array. I would try changing the if statement
if(sample_text === '') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);
to something like
if(sample_text['dismiss'] == 'cancel') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);

Remove an item from User's cart after 30 minutes with PHP and Javascript

I have a typical ecommerce site with a shopping cart and I want to automatically remove an item from a user's cart after 30 minutes (or some other defined time period). I'm really unsure of the best way to accomplish this. I know that there is the php sleep() function, but it seems that would be an undesirable method for waiting 30 minutes or more from a performance standpoint. I tried setting a timeout in my javascript using setTimeout() and had it call a function that would send an Ajax call to removefromcart.php along with the item's id. However, I was unsuccessful at getting that to fire at all. Below is the code used to add the item to the cart:
session_start();
require_once('../config.php');
try{
$itemId = array_key_exists('itemId', $_POST) ? $_POST['itemId'] : null;
if(!is_null($itemId)){
if(!in_array($itemId, $_SESSION['cart'])){
$i = count($_SESSION['cart']);
$_SESSION['cart'][$i] = $itemId;
$sql = "UPDATE
titems
SET
intInactive = 1
WHERE
intItemId = ? ";
$stmt = $conn->prepare($sql);
$stmt->execute([$itemId]);
echo ("Success");
$_SESSION['cart_count'] = count($_SESSION['cart']);
}
}
} catch(Exception $ex) {
error_log($ex->getMessage());
logError($conn, 'ADD TO CART FAILED. Error: '. $ex->getMessage());
echo("Fail");
}
Here is the Javascript used to fire this event:
// Add Item to Cart
$('button.addtocart').on('click', function(){
var btnId = this.id;
var itemId = btnId.split('-')[1];
$.ajax({
method: 'POST',
url: 'Backend/addtocart.php',
data: {itemId: itemId},
success: function(data){
if(data == 'Success'){
swal({
title: "Item Added!",
text: "my message",
type: "success",
confirmButtonText: "OK"
},
function(isConfirm){
if (isConfirm) {
$("#row-"+itemId).fadeOut("slow");
location.reload();
}
});
} else {
swal({
title: "Error!",
text: "Something Went Wrong! Please Try Again.",
type: "error",
confirmButtonText: "OK"
});
}
}
})
})
Javascript for removing an item when the user clicks "Remove From Cart", I'm hoping to use a similar Ajax call to accomplish my auto-removal:
// Remove Item From Cart
$('#CartTable :button').on('click', function(){
var btnId = this.id;
var itemId = btnId.split('-')[1];
swal({
title: "Remove?",
text: "Are you sure you want to remove this item from your cart?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, remove it!",
cancelButtonText: "No, keep it!",
closeOnConfirm: false
},
function(isConfirm){
if (isConfirm) {
swal("Removed!", "That item has been removed from your cart!", "success");
location.reload();
$.ajax({
method: 'POST',
url: 'Backend/removefromcart.php',
data: {itemId: itemId},
success: function(data){
if(data == 'Success'){
swal({
title: "Success!",
text: "Item Successfully Removed From Cart",
type: "success",
confirmButtonText: "OK"
});
$("#row-"+itemId).fadeOut("slow");
} else {
swal({
title: "Error!",
text: "Something Went Wrong! Please Try Again.",
type: "error",
confirmButtonText: "OK"
});
}
}
})
} else {
swal("Cancelled", "Too good to let go!", "error");
}
}
);
})
And finally, here is the php used to actually remove the item from the cart:
session_start();
require_once('../config.php');
try{
$itemId = array_key_exists('itemId', $_POST) ? $_POST['itemId'] : null;
if(!is_null($itemId)){
$i = array_search($itemId, $_SESSION['cart']);
unset($_SESSION['cart'][$i]);
$sql = "UPDATE
titems
SET
intInactive = 0
WHERE
intItemId = ? ";
$stmt = $conn->prepare($sql);
$stmt->execute([$itemId]);
echo ("Success");
$_SESSION['cart_count'] = count($_SESSION['cart']);
}
} catch(Exception $ex) {
error_log($ex->getMessage());
logError($conn, 'REMOVE ITEM FROM CART FAILED. Error: '. $ex->getMessage());
echo("Fail");
}
I'm really hoping to utilize the code that I already have in place to accomplish this task. I hope someone can help me out! Thanks.

Login validation not working on HTML using JSON and PHP

I am making a login form on HTML using JSON and PHP but all of the if statements on success are not working but the beforeSend and error is working. Can you help me check my mistakes?
I dont know know what is wrong with the function on success. The alerts are not popping up. For example response.success == true is supposed to pop up ' You are successfully logged in... '
<script>
$(document).ready(function(){
$('#loginForm').on('submit',function(e){
var myForm = new FormData($(this)[0]);
$.ajax({
type:'POST',
url: 'connections/login.php',
data : new FormData($(this)[0]),
cache: false,
contentType:false,
processData: false,
beforeSend: function(){
$("div#divLoading").show();
},
success: function(response){
$("div#divLoading").hide();
console.log(response);
if(response.success == true)
{
alert(' You are successfully logged in... ')
}
else if( response.success == false ){
alert('please enter a correct email & password');
}
else{
if(response.matric){
alert('email is wrong');
}
if(response.password){
alert('password is wrong');
}
}
},
error: function(data){
alert('error');
$("div#divLoading").hide();
}
});
return false;
});
});
</script>
Here is my PHP:
<?php
require_once('connect.php');
session_start();
header('Content-Type: application/json');
if (!empty($_POST['matric']))
{
$matric=$_POST['matric'];
$password=$_POST['password'];
$pass= $dbh->prepare("SELECT * FROM users WHERE matric=:matric AND password=:password");
$pass->bindParam(':matric', $matric);
$pass->bindParam(':password', $password);
$pass->execute();
if($pass->fetch(PDO::FETCH_NUM) > 0)
{
$_SESSION['matric']=$matric;
$response = array(
'success' => true,
'message' => 'Login successful');
}
else
{
$response = array(
'success' => false,
'message' => 'Login fail');
}
}
echo json_encode($response);
echo json_encode($_POST);
?>
You have
echo json_encode($response);
echo json_encode($_POST);
which is going to issue corrupted JSON. e.g. your output is going to be
{"success":true,"message":"Login successful"}Array
^^^^^^---corruption
Since your JSON is corrupted, it won't decode properly, and response WON'T be what you think it is.
Remove this line:
echo json_encode($_POST);

how to get the return message from store.sync();

function onButtonClick(){
var grid = Ext.getCmp('mygridpanel')
var row = grid.getSelectionModel().getSelection()[0];
var txtVehicleID = Ext.getCmp('txtVehicleID').getValue();
var txtPlat_No = Ext.getCmp('txtPlat_No').getValue();
console.log(txtVehicleID);
var record = UserStore.findRecord('_id', txtVehicleID);
record.set('_id', txtVehicleID);
record.set('Plat_No',txtPlat_No);
UserStore.sync({
success: function(response) {
Ext.MessageBox.show({
title: "Information",
msg: "Update Success !",
icon: Ext.MessageBox.INFO,
buttons: Ext.MessageBox.OK,
fn: function(buttonId) {
if (buttonId === "ok") {
EditWin.close();
}
}
});
},
failure: function(action){
Ext.MessageBox.show({
title: "Information",
msg: "Update Failed !",
icon: Ext.MessageBox.ERROR,
buttons: Ext.MessageBox.OK,
fn: function(buttonId) {
if (buttonId === "ok") {
EditWin.close();
}
}
});
}
});
//console.log("clicked");
}
php return success message string
<?php
$data = file_get_contents("php://input");
//echo $data;
//$obj = var_dump(json_decode($data));
$obj = json_decode($data);
$_id = $obj->{'_id'};
$Plat_No = $obj->{'Plat_No'};
mysql_connect("localhost", "root", "Apacheah64") or die("Could not connect");
mysql_select_db("db_shuttlebus") or die("Could not select database");
$query = "UPDATE tbl_vehicle SET Plat_No ='". $Plat_No ."' WHERE _id=".$_id;
if (mysql_query($query)){
echo '{"success":true,"message":"Update Success !"}';
}else{
echo '{"success":false,"message":"Update Failed !"}';
}
?>
how to get the message and show at here msg: "Update Success !" ?
In your UserStore.sync() config object try to define success an failure handlers like this:
UserStore.sync({
success: function(batch, options) {
var message = batch.proxy.getReader().jsonData.message;
// display success message...
},
failure: function(batch, options) {
var message = batch.proxy.getReader().jsonData.message;
// display error message...
}
});

Categories