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);
Related
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
I have used Django2 to develop a web app.
I frontend, after the ajax call, the network tab on chrome dev does show the 200 status code, but I did not see any alert box. my app stuck at this line for waiting json: const msg_json = await response.json(); , the following alert does not execute
async function myFunction() {
Swal.fire({
title: '',
text: "Do you want to confirm entries?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
cancelButtonText: 'No'
}).then(
async(result) => {
if (result.value) {
$.ajax({
url: '/content_checklist_name_url/',
type: 'POST',
data: $(this).serialize(),
cache: false,
success: function(data) {
var comment_html = "<div id='myform_1'>" + data['log_info'] + "</div>";
$('#myform_1').remove();
$('#ajax_data').prepend(comment_html);
$('#myform_input').val('');
},
});
const response = await fetch({ % url 'bms:content_checklist_name_url' %
});
const msg_json = await response.json();
alert(msg_json.responseText)
let a = msg_json;
if (a === "Duplicate Entry. This Course Code already exists.") {
Swal.fire({
title: '',
text: 'Duplicate Entry. This Course Code already exists.',
type: 'error',
})
} else {
Swal.fire({
title: '',
text: 'Entries have been saved.',
type: 'success',
})
}
// },
// failure: function(data)
// {
// alert('Got an error dude');
// }
// });
} else {
window.stop();
}
}
)
}
<form id="myform" action="/content_checklist_name_url/" method="POST">
...
</form>
<button class="button" onclick="myFunction()" type="button" id="submit">SUBMIT</button>
backend view.py:
#csrf_exempt
def content_checklist_name_url(request):
if request.method == 'POST':
...
msg = "success"
obj = {"msg": msg}
context = {'msg_json': json.dumps(obj)}
return render(request, 'bms/main.html',context=context)
I got the error in the console: VM355:4 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 3
no alert box shows.
How could I check where goes wrong?
Your view is waiting for a POST and you are sending a GET so this branch won’t be executed. Also, submitting a form by html, make the browser change pages so as the form is submitted, the ajax won’t be called.
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');
}
}
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.
Sweet alert is showing status of wrong password if i enter wrong passwords that is correct but then if i make them right it still showing status of wrong passwords not getting what is problem
Php code
if($new_pass_hash != $pass_hash){
echo"Current password is wrong";
exit();
}else{
$updated_pass_hash = sha1($enew.$salt);
$update_pass = " UPDATE vendor SET pass_hash = '$updated_pass_hash' WHERE vd_id='$vd_id'";
$run_update = mysqli_query($con, $update_pass);
echo"Updated";
}
Response
$.ajax({
type:"POST",
data: "pass=" +pass + "&enew="+enew+"&repeat="+repeat,
url:"phpfiles/edit-password.php",
success: function(data){
if(data =='Updated'){
swal({
title: 'Success',
text: 'Password updated successfully' ,
imageUrl: "icons/thumbs-up.jpg"
},
function(){
window.location.href = 'docs.php';
});
}else{
swal({
title: 'Error',
text: 'Current password is wrong',
type: 'error'
});
}
}
});
return false;