Sweetalert submit inputValue with ajax and php - javascript

I have a sweetalert modal that allows users input a pin.
I have also validated it, but anytime i try sending the data to a php page.
The page dosent get the data. here is sample of my code.
Index page
<script>
$(document).ready(function(){
swal({
title: "Setup Transaction pin",
text: "Enter a memorable 4digit pin to keep your account safe and make sure every transactions comes from you.",
type: "input",
showCancelButton: false,
closeOnConfirm: false,
animation: "slide-from-top",
inputType: "number",
inputPlaceholder: "Enter a pin"
},
function(inputValue){
if (inputValue === null){
swal.showInputError("Please enter a pin!");
return false
}
if (inputValue === "") {
swal.showInputError("Please enter a pin!");
return false
}
if (inputValue.length !== 4) {
swal.showInputError("Pin must be 4digits!");
return false
}
var pin = inputValue.toString();
$.ajax({
url: './backend/edit-profile?action=register_pin',
type: 'POST',
data: {
pin: pin
},
dataType: "json",
cache: false,
contentType: false,
processData: false,
success : function(data){
if (data.code == "200"){
swal({
title: data.msg,
//text: data.msg+inputValue" \n",
type: "success",
});
} else {
swal({
title: data.msg,
// text: data.msg+" \n",
type: "error",
});
}
}
});
// swal("Nice!", "You wrote: " + inputValue, "success");
});
});
</script>
Php code
<?php
if($action == "register_pin"){
$pin = $_POST['pin']);
if(empty($pin) || strlen($pin) !== 4){
$data['msg'] = "Enter a pin $pin";
}else{
$data['code'] = 200;
$data['msg'] = "You entered $pin";
}
}
?>
Everything works fine except the value. The php code dosent echo the inputValue

Related

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);

How to disappear trails of first dialog when I open new sweet alert dialog?

I have a delete button when user click it I want a sweet alert which asks for confirmation and once the user click yes and confirm then I want to disappear current confirmation alert and show another alert which tells user deleted and then after 2 seconds page reloads.
i have done it but my issue is when user click on confirmation alert he get the another alert but with some trails of previous alert. (this is the snip showing trails in red boxe) (I did not uploaded them here because I can not due to reputation).
my js is
function deleteUser(userRow) {
var objUserRow = jQuery.parseJSON(unescape(userRow));
swal({
title: "Are you sure?",
text: "You will not be able to recover this user again",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
closeOnClickOutside: false,
}, function (isConfirm) {
if (isConfirm) {
$.ajax({
url: '../users/deleteUser',
type: 'POST',
data: objUserRow,
success: function (data) {
if (data == "success") {
//swal("User Deleted!");
swal({
title: "Deleted!",
text: "User has been deleted successfully!",
type: "success",
showConfirmButton: false,
closeOnClickOutside: false
});
setTimeout(function () { location.reload(); }, 2000);
} else if (data == "error") {
//this could be due to server side validation or server side error
swal("Error!", "An error has occured at server side", "error");
}
},
error: function () {
swal("Error!", "An error has occured at server side", "error");
}
});
}
});
}
I can not get what I am doing wrong. Please help
Try to use promises
https://sweetalert.js.org/guides/?_sm_au_=i0HmMJQJFSN6506q#using-promises
swal({
title: "Are you sure?",
text: "You will not be able to recover this user again",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
closeOnClickOutside: false,
}).then((isConfirm) => {
if (isConfirm) {
$.ajax({
url: '../users/deleteUser',
type: 'POST',
data: {},
success: function (data) {
if (data == "success") {
//swal("User Deleted!");
swal({
title: "Deleted!",
text: "User has been deleted successfully!",
type: "success",
showConfirmButton: false,
closeOnClickOutside: false
});
setTimeout(function () { location.reload(); }, 2000);
} else if (data == "error") {
//this could be due to server side validation or server side error
swal("Error!", "An error has occured at server side", "error");
}
},
error: function () {
swal("Error!", "An error has occured at server side", "error");
}
});
}
});
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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.

How to insert sweet alert type input into database

I want to insert the inputValue of sweetalert into my database. I have a query to insert:
swal("Nice!", "Notes: " + inputValue, "success");
But it doesn't work
My code:
function show_confirm_delete<?=$data->proposalID?>(){
setTimeout(function () {
swal({
title: "Yakin ingin me-reject Proposal?",
text: "Beri alasan kenapa anda mereject proposal ini.",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Tulis disini"
},
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "Notes: " + inputValue, "success");
window.location.href = "proses-reject.php?id=<?=$data->proposalID?>";
}); }, 1);}
Please help me. Thanks!

sweetalert dialog box with textbox in Chrome

I am having an issue with sweetalert dialog box with text field in chrome.
It works just fine in mozila but does not works in chrome.
Alert box works but does not allow to enter a value in texbox.
below is the jquery
function sendmail(val){
swal({
title: "Send E-Mail",
text: "<input type='email' class='form-control' name='email' id='email'/>",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Send",
html: true,
closeOnConfirm: false
},
function (isConfirm) {
if (isConfirm) {
var email = $("#email").val();
var dataString = 'email=' + email + '&id=' + val;
$.ajax({
type: "POST",
url: "../class/sendmail.php",
data: dataString,
cache: false,
success: function (result) {
swal("sent!", "Your Mail has been sent.", "success");
}
});
}
});}
I think it's two things, firstly you're using sweet alert's input wrong. You want to change the type of the sweet alert to input.
swal({
title: "An input!",
text: "Write something interesting:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something" },
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "You wrote: " + inputValue, "success");
});
That's taken from the example on the sweetalert Website
Also as you're adding the input#email after DOM load you need to use something like jQuery's .on() functionality.

Categories