Trying to add a CC or similar to email function - javascript

Currently this function emails the person who inputs their email in the text field and the sender is our API ecommerce email. The To: is the person who made the request.
My trouble is I can't seem to add possibly a CC: field to also add so we know who made the request.
Below is the function, there's more to it that I can provide if needed.
$('#emailCart').click(function(e) {
e.preventDefault();
Swal.fire({
title: 'Enter Email',
input: 'text',
showCancelButton: true,
confirmButtonText: 'Email Cart',
preConfirm: (email) => {
if (email.length === 0 || !emailIsValid(email)) {
Swal.showValidationMessage('Please enter a valid email address.');
}
}
}).then((result) => {
if (result.value) {
$.ajax({
url: apiUrl + '/cart/email',
method: 'post',
headers: {
'X-CSRF-TOKEN': csrfToken
},
data: {
email: result.value
},
success: function() {
Swal.fire({
type: 'success',
title: 'Success',
text: 'Your cart has been emailed.',
timer: 1500
});
},
error: function() {
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Cart could not be emailed.'
})
}
});
}
});
});

Related

Sweetalert submit inputValue with ajax and php

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

How do I pass through text inputted in SweetAlert2 box to a .then method?

Right now I am doing the following:
function resetPassword(email) {
/* The following is for the alert dialog box that is triggered when the user
presses forget password! */
Swal.fire({
title: 'Enter the email address',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Send Reset Email',
}).then((input) => {
firebase.auth().sendPasswordResetEmail(email)
.then(() => {
Swal.fire({
title: 'Email Sent!',
text: 'Check your email for a reset link!',
type: 'success',
confirmButtonText: 'Cool'
});
})
.catch((error) => {
Swal.fire({
title: 'Error!',
text: error.message,
type: 'error',
confirmButtonText: 'Cool'
});
});
});
}
But it is not working, what am I doing wrong?
My main outcome is to get the email, pass it through to firebase auth api, send the email, then put one more diag box out that says "done" basically. But the input is not coming through. Why is this?
Thanks in advance.
The Swal result will be stored in an object with the same name that you define in the passed parameter to the 'then' function, in this case, input. The email address is stored in input.value. I'd also remove the unnecessary email parameter from the function declaration. This should work:
function resetPassword() {
/* The following is for the alert dialog box that is triggered when the user
presses forget password! */
Swal.fire({
title: 'Enter the email address',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Send Reset Email',
}).then(({value: input}) => {
firebase.auth().sendPasswordResetEmail(input)
.then(() => {
Swal.fire({
title: 'Email Sent!',
text: 'Check your email for a reset link!',
type: 'success',
confirmButtonText: 'Cool'
});
})
.catch((error) => {
Swal.fire({
title: 'Error!',
text: error.message,
type: 'error',
confirmButtonText: 'Cool'
});
});
});
}
Thank you for your answer #Chris, but after yours not working I then went onto the SA2 docs and found a login page, then heavily modified it to the following:
function resetPassword() {
/* The following is for the alert dialog box that is triggered when the user
presses forget password! */
Swal.fire({
title: 'Please Enter Your Email Address',
html: `<input type="text" id="email" class="swal2-input" placeholder="mail#website.com">`,
confirmButtonText: 'Sign in',
focusConfirm: false,
preConfirm: () => {
const email = Swal.getPopup().querySelector('#email').value
return { email: email }
}
}).then((result) => {
firebase.auth().sendPasswordResetEmail(result.value.email)
.then(() => {
Swal.fire({
icon: 'success',
title: 'Email Sent!',
text: 'Check your email for a reset link!',
type: 'success',
confirmButtonText: 'Cool'
});
})
.catch((error) => {
Swal.fire({
title: 'Error!',
text: error.message,
type: 'error',
confirmButtonText: 'Cool'
});
});
});
}
Thanks for your help though and the solution which I am posting now did take a long time to make so you are still greatly appreciated.
Have a nice day!

How to show loading function before get data from server?

I use Ajax and SweetAlert2 library to use alert UI. I search the how can I show the loading process during get data from server and I thought I can use beforeSend function. I write code like this.
So I put the Loading Process code inside the beforeSend but I don't know why It's not working. So I want to check is it works in beforeSend code so I write console.log code inside it and it actually works. But I don't know why the Swal.showLoading(); code is not working.
When I just type it in google console it works.
Loading Code is Simple.
Swal.showLoading();
And I want When it finish it show Finish Code.
/* Mypage */
function getData() {
Swal.fire({
title: 'Do you want to get data from Github?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
allowOutsideClick: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Get DATA!'
}).then((result) => {
if (result.value) {
$.ajax({
type: "POST",
// contentType: "application/json",
url: `/${userId}/admin/getData`,
dataType: "json",
beforeSend: function () {
Swal.showLoading();
console.log('Loading');
},
success: function (redrawData) {
console.log(JSON.stringify(redrawData));
let existTable = $('#dataTable').DataTable();
existTable.destroy();
$('#dataTable').DataTable({
aaData: redrawData, // Returned Data from Server
aoColumns: [{
mData: 'id',
"render": function (value, type, row) {
return `${row.id}`;
}
},
{
mData: 'name'
},
{
mData: 'type'
},
{
mData: 'url'
},
{
mData: 'imgurl',
"render": function (value, type, row) {
return `<img src="${row.imgurl}">`;
}
},
{
mData: 'sumlang'
},
{
mData: 'pjdate1'
},
{
mData: 'pjdate2'
},
{
mData: 'githuburl'
}
]
})
},
complete: function () {
Swal.fire(
'Get!',
'Your file has been deleted.',
'success'
)
},
error: function (e) {
Swal.fire(
'Failed to save',
'If this message is output continuously, please contact to administrator.',
'error'
)
}
});
}
})
}
I never used SweetAlert but I have taken a look on their website exmaple and found this
const ipAPI = 'https://api.ipify.org?format=json'
Swal.queue([{
title: 'Your public IP',
confirmButtonText: 'Show my public IP',
text:
'Your public IP will be received ' +
'via AJAX request',
showLoaderOnConfirm: true,
preConfirm: () => {
return fetch(ipAPI)
.then(response => response.json())
.then(data => Swal.insertQueueStep(data.ip))
.catch(() => {
Swal.insertQueueStep({
type: 'error',
title: 'Unable to get your public IP'
})
})
}
}])
They use fetch with preConfirm in their exmaple, but in your case, I guess you can try to use preConfirm attribute that return the Promise created by the JQuery $.ajax() function
Example:
/* Mypage */
function getData() {
Swal.fire({
title: 'Do you want to get data from Github?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
allowOutsideClick: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Get DATA!',
showLoaderOnConfirm: true,
allowOutsideClick: () => !Swal.isLoading(),
preConfirm: function(){
return $.ajax(...); //Your ajax function here
}
});
}
You could just set the showLoaderOnConfirm to true to show the preloader when you click the continue button. Then, add the ajax call inside the preConfirm. Just make sure to return the response and catch any errors.
Swal.fire({
title: 'Submit your Github username',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Look up',
showLoaderOnConfirm: true,
preConfirm: (login) => {
return fetch(`//api.github.com/users/${login}`)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
.catch(error => {
Swal.showValidationMessage(
`Request failed: ${error}`
)
})
},
allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
if (result.value) {
Swal.fire({
title: `${result.value.login}'s avatar`,
imageUrl: result.value.avatar_url
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8"></script>

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

AJAX call with error catching in SweetAlert2

I'm scratching my head for a couple of days now and I can't get SweetAlert2 to do a AJAX call and return "Success" if it succeeded or show me an error in the same box if something goes wrong, leaving the user free to try again.
My implementation is following so far. The problem is that it shows the error in the box, but closes it at the same time:
swal({
title: 'Submit?',
text: 'Are those informations correct?',
type: 'question',
showCancelButton: true,
confirmButtonText: 'Absolutely',
cancelButtonText: 'Not sure',
showLoaderOnConfirm: true,
preConfirm: function() {
return new Promise(function(resolve,reject) {
$.ajax({
url: '*****', // Invalid URL on purpose
type: 'POST',
data: {test: true}
})
.done(function(data) {
resolve(data)
})
.fail(function() {
reject()
});
})
},
allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
if (result.value) {
swal({
title: `Success`,
text: result.value
})
}
}).catch((result) => {
swal.showValidationError('POST failed. Please try again.');
})
In the documentation I cannot find a AJAX call with a showValidationError. The closest I found is a fetch() call, but those are only for GET, as far as I know.
I also tried something like: return true, return false, throw new Error, promises inside promises, but that was all trial-and-error, so I came here.
I also made a fiddle: https://jsfiddle.net/xpvt214o/306267/
Thanks in advance for any help and/or suggestions.
After one more day I figured it out. I had to .then and .catch the $.ajax and attach swal.showValidationError on it in order to work.
On a AJAX error it will show following in the same box now (The user can try as many times as he pleases):
On success following:
swal({
title: 'Submit?',
text: 'Are those informations correct?',
type: 'question',
showCancelButton: true,
confirmButtonText: 'Absolutely',
cancelButtonText: 'Not sure',
showLoaderOnConfirm: true,
preConfirm: () => {
return $.ajax({
url: '***',
type: 'POST',
data: 'test'
})
.then(response => {
return response
})
.catch(error => {
//console.log(error); // Nice to view which properties 'error' has
swal.showValidationError(
`An error ocurred: ${error.status}`
)
})
},
allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
if (result.value) {
swal({
type: 'success',
title: 'Success',
text: result.value
})
}
})
Fiddle: https://jsfiddle.net/z3kfhsj8/6/

Categories