i am trying to use sweetAlert2 for my ajax, creating a form inside and then do its process and get the results back, but i am stuck at one point which is when i send the results how do i process the ajax inside it,
Here is my code as of now
Swal.fire({
title: 'Request PlayForm',
html: `<textarea name="da" id="da"></textarea>`,
confirmButtonText: 'Submit',
focusConfirm: false,
preConfirm: () => {
const textData = Swal.getPopup().querySelector('#da').value
if (da== '') {
Swal.showValidationMessage(`Please enter details.`)
}
return { da: da}
}
}).then((result) => {
Swal.fire(`
Email Sent Successfully -- this message should come when i get a success from my ajax else it will display error which i can get from ajax
`.trim())
})
CodePudding user response:
You can do it like this.
Swal.fire({
title: 'Request PlayForm',
html: `<textarea name="da" id="da"></textarea>`,
confirmButtonText: 'Submit',
focusConfirm: false,
preConfirm: () => {
const textData = Swal.getPopup().querySelector('#da').value;
if(!textData || !textData.trim()) {
Swal.showValidationMessage(`Please enter details.`)
}
return textData;
}
}).then((result) => {
var myResult = result.value;
console.log("calling ajax");
$.ajax({
url: 'https://pokeapi.co/api/v2/pokemon/' myResult,
//data: {'da':myResult}, <== use this if you're sending any data
type: 'get', // or post, depending what you do in the background,
// dataType: 'json' - data type of your response. It's optional,
// you can set it to something else, like text, or application/pdf,
//or something else
beforeSend: function() {
console.log("this is before send - we want to get some info " myResult);
// disable buttons to prevent double clicks,
// or do something else
},
success: function(data) {
// Process the response - data
// Send mail if successful
if(data) {
Swal.fire(`
Email Sent Successfully -- this message should come
when i get a success from my ajax else it will display
error which i can get from ajax
`.trim());
console.log(data);
} else {
Swal.fire(`There was an error: ` /* your error here*/);
}
},
error: function(desc, err) {
Swal.fire(`
AJAX error! Description: ` JSON.stringify(desc) `,
error: ` JSON.stringify(err));
}
});
// END AJAX
});
// END .then(...)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
The variable myResult
(you can name it whatever you like) stores the result of da
/ return of your preconfirm
. You could process it later on, to see if it matches what you expect (for example, whether there were any illegal characters, or if you were expecting a number, or a certain format, but the user decided to be cheeky and type in something else, etc).
If the input was alright, you move on to the else
part in the .then(...)
, and call your AJAX there. Read the comments in the code for more info.