sweetalert ajax functionality - javascript

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())
})

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.

Related

JavaScript - Multiple Overlapping Async GET Requests?

I have tried ways to search for a solution but I can't seem to find the right combination of words or something... here goes:
I have an ASP.NET MVC application that users scan inventory/package barcodes into. Every time someone scans an item, I make an async request and then display a popup message with information about the package. This part works as expected and does not block the application during the request:
$.ajax({
type: 'GET',
dataType: 'json',
async: false,
url: '#Url.Action("SingleOrderLookup")?trackingNumber=' + trackingId,
success: function (result) {
if (result.success) {
var audio = findAudio(result.model, audioClips, saturdayAudio);
suppressDefaultSound = true;
var titleText = result.model.displayPromptText;
if (result.model.isRefrigerated) {
isRefrigerated = true;
titleText = "<p style='color: blue;'>(REFRIGERATED)</p>" + "<p>" + result.model.displayPromptText + "</p>";
}
swal.fire({
title: titleText,
text: "Place in route for " + result.model.displayPromptText,
type: "success",
showCancelButton: false,
confirmButtonText: "Sorted",
cancelButtonText: "Cancel",
timer: 1750,
preConfirm: function () {
return new Promise(function (resolve) {
resolve();
}, 1000);
}
}).then(result => {
if (result.value) {
}
});
var dupe = findOrderByTrackingNumber(trkNumbers, result.model.trackingId);
if (!dupe) {
trkNumbers.push({ trackingNumber: trackingId, depotId: result.model.destinationHub });
pkgCount++;
if ($("#divUpdatePickup").is(":hidden"))
$("#divUpdatePickup").show();
AddLogToTable(trackingId);
} else {
//audible feedback that duplicate was scanned
//if (!trkBin) PlayAudio(2);
//PlayAudio(2);
}
//playing audio
if (isRefrigerated) {
setTimeout(function () {
if (audio) playByteArray(audio);
}, 1500);
PlayRefrigerate();
} else {
if (audio) playByteArray(audio);
}
}
if (result.nullRoute) {
addToTrkNumbers = false;
Swal.fire({
title: "NO ROUTE DEFINED",
text: "Unable to match order to a route!",
type: "warning",
showCancelButton: false
});
}
}
});
However, I want the page to make another async call to populate a variable with an array of objects, transparently and without blocking the user from making scans and receiving information back from the async calls from the above code. This call should occur immediately when the page is loaded, and it could take more than a minute or two to receive all the data expected from this call. Once the response is back, the collection variable (zipSort[]) should be populated. The data in this variable will contain a "cache" of elements that the page can query against to avoid having to make individual server-side calls after each scan (in essence, I want to "front-load" data needed for the scan events and once completed, individual calls to the server should not be necessary since this variable should contain 99% of the IDs expected to be scanned).
This is where I'm having an issue and it's probably due to a lack of understanding of how async calls/JS promises work. Here is the code I have so far for this:
//array to hold data on expected tracking number scans
var zipSort = []
async function getCheckinGroup(zipSort) {
console.log("Fetching complete check-in group...");
var url = '/SortFacility/HubManager/GetOrders';
var promise = new Promise((resolve,reject) => {
$.ajax({
type: "GET",
url: url,
cache: false,
async: true,
contentType: "application/json",
success: function (result) {
if (result.success) {
console.log("Retrieval success");
try {
zipSort = result.model;
resolve(result.model);
} catch (ex) {
reject("Some error?");
}
} else {
reject("Some error?");
}
},
error: function (ob, errStr) {
reject("Something went wrong");
}
});
});
return promise;
}
//don't want this to hold up execution of the rest of the code, so zipSort[] should
//remain empty and get set transparently when the ajax response is returned:
getCheckinGroup(zipSort);
Every version of code I'm trying out from articles and tutorials I have read holds up the UI and keeps users from being able to scan items while the response hasn't been returned. What am I missing? How should I change this so that (a) users can begin scanning immediately once the page has loaded and receive information from individual async calls to the DB, and (b) zipSort[] can be populated with the totality of any data potentially needed for these scans, and once populated, scan events trigger a lookup on that variable instead of continued individual calls to the database?
Any help would be appreciated!
Edit: tried simply adding this call in-line and no matter where I put it, it blocks the other code from running until response is received, even though async is set to true:
$.ajax({
type: "GET",
url: url,
cache: false,
async: true,
contentType: "application/json",
success: function (result) {
console.log("Data received.");
zipSort = result.model;
}
});
Thanks everyone for your help. I found this little gem, which solved my problem:
https://josef.codes/c-sharp-mvc-concurrent-ajax-calls-blocks-server/
Applying [SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)] to my controller class enabled concurrent async ajax calls.

after ajax call , the code after waiting for Json response could not be executed

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.

JQuery confirmation dialog after AJAX request

I need to validate, on server side, if a person with a given registration number is already on the database. If this person is already registered, then I proceed with the program flow normally. But, if the number is not already registered, then I'd like to show a confirmation dialog asking if the operator wants to register a new person with the number entered and, if the operator answers yes, then the person will be registered with the number informed on the form on it's submission.
I've tried
Server side(PHP):
if (!$exists_person) {
$resp['success'] = false;
$resp['msg'] = 'Do you want to register a new person?';
echo json_encode($resp);
}
Client side:
function submit(){
var data = $('#myForm').serialize();
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
return false;
}
I can't even see the alert, that's where I wanted to put my confirmation dialog, with the message written on server side. Other problem, how do I resubmit the entire form appended with the operator's answer, so the server can check if the answer was yes to register this new person?
EDIT
I was able to solve the problem this way:
Server side(PHP):
$person = find($_POST['regNo']);
if ($_POST['register_new'] === 'false' && !$person) {
$resp['exists'] = false;
$resp['msg'] = 'Do you want to register a new person?';
die(json_encode($resp)); //send response to AJAX request on the client side
} else if ($_POST['register_new'] === 'true' && !$person) {
//register new person
$person = find($_POST['regNo']);
}
if($person){
//proceed normal program flow
}
Client side:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
var ajax1 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function (response) {
if (!response.exists && confirm(response.msg)) {
document.getElementById('register_new').value = 'true'; //hidden input
dados = $('#myForm').serialize(); //reserialize with new data
var ajax2 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function () {
document.getElementById('register_new').value = 'false';
$('#myForm').unbind('submit').submit();
}
});
} else if (response.success) {
alert(response.msg);
$('#myForm').unbind('submit').submit();
}
}
});
}
There doesn't appear to be anything wrong with your PHP.
The problem is (1) You are doing the alert inside of an error callback, and your request isn't failing, so you don't see the alert. (2) You are alerting the string 'response' instead of the variable response.
It is also worth noting that you should be using the .done() and .fail() promise methods (http://api.jquery.com/jquery.ajax/#jqXHR).
Here is the fixed JS:
function submit() {
var data = $('#myForm').serialize();
// Same as before, with the error callback removed
var myAjaxRequest = $.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
});
// The request was successful (200)
myAjaxRequest.done(function(data, textStatus, jqXHR) {
// The data variable will contain your JSON from the server
console.log(data);
// Use a confirmation dialog to ask the user your question
// sent from the server
if (confirm(data.msg)) {
// Perform another AJAX request
}
});
// The request failed (40X)
myAjaxRequest.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
return false;
}
Also, you are setting a 'status' in PHP and checking that in the JS (I presume). What you want to be doing is setting a HTTP status code from the server, as below:
if (!$exists_person)
{
$resp['msg'] = 'Do you want to register a new person?';
// 400 - Bad Request
http_response_code(400);
echo json_enconde($resp);
}
Then, jQuery will determine whether the request failed based on the status code you respond with. 200 is a successful request, and 400 numbers are fail.
Check out this page for a full list: https://httpstatuses.com/
Okay so this is a two part question; I'll try my best to answer both parts:
Part 1: How to detect if success is false and trigger the confirmation popup?
In jQuery.ajax the error handler is triggered based on response code. This is probably not what you want. You can use your success handler and test the value res.success to see if it's true or false. It would be something along the lines of:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
}).done(function(res) {
if (!res.success) {
alert(res.msg);
}
});
}
Part 2: How do I resubmit with a confirmation?
Working off of our previous code we will make some changes that allow for submit() to be passed an argument registerNew. If registerNew is true we will pass it as a param to the ajax handler in the PHP so it knows we want to register a new person. The Javascript will look something like this:
function submit(e, registerNew) {
if (e) e.preventDefault();
var data = $('#myForm').serialize();
var ajax_options = {
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
};
ajax_options.data.register_new = !!registerNew;
$.ajax(ajax_options).done(function(res) {
if (!res.success && confirm(res.msg)) {
submit(null, true);
}
});
}
As you can see here, we are passing a new register_new param in the data in our ajax options. Now we need to detect this on the PHP side, which is easy enough and looks like this (this goes in your php ajax handler):
if ($_POST["register_new"]) {
// new user registration code goes here
} else {
// your existing ajax handler code
}
Add confirm inside submit function
function submit(){
var data = $('#myForm').serialize();
if (confirm('Are you ready?')) {
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
}
return false;
}

AJAX data contains one or more words..?

I'm using an AJAX post to submit form data and this is working well.
I'm not trying to show an message based on success or failure..
I've got this so far:
alert("Yehh.. Saving Data.");
$.ajax({
url:'go.php?doit=1',
data:$("form").serialize(),
type:'POST' })
.done(function(data) {
console.log(data);
})
When the submit completes data will contain either nothing or the text back from the update saying why it failed.
As an example I'd like to show an alert if there are no errors returned.
Any idea how I can do that?
If there are errors, I'd like to show an different alert.
I would return a response from the server in both cases, just to be safer...
but it will work if you don't, unless the server had a problem, no string was returned and you assumed you had a success! Do you see the problem here?
On the server:
Success:
$response = {
'status': 1,
'message': 'Success'
}
Error:
$response = {
'status': 0,
'message': 'Some error'
}
The Ajax function:
$.post( "go.php?doit=1",
{
data : $("form").serialize()
},
function(data) {
if(data.status == 1){
// success! Do something
}
else{
// error! Do something! eg: alert message
alert(data.message)
}
});
Assuming you mean that your HTTP request is sending, and that you are evaluating deliberate return values (for example you are validating your form, and returning an empty string to signify an error), you can do the following:
JS:
alert("Yehh.. Saving Data.");
$.ajax({
url: 'go.php?doit=1',
data: $("form").serialize(),
type: 'POST'
})
.done(function (data) {
if ( typeof data !== 'string' )
console.log("data is not a string. Consider 'return false' if this is unexpected?")
if ( data.length > 0 )
console.log("There was data returned")
if ( data.length === 0 )
console.log("Empty string returned!")
})
It might be a better idea to return a JSON object with the exact data you are trying to pass (such as a valid or fail flag, along with a message)

Json result prompting download

I am implementing a simple CRUD operating. I have List of data displayed in table with capability of add edit and delete. Add edit and delete operation takes place in Jquery dialog
When i am trying to add a new record I return the Json result as Success True/false depending on the form data entry.
Here is my code
[HttpPost]
public ActionResult AddUser(AddCEQRUser addUserInfo)
{
// perform insert operation
if (ModelState.IsValid && InsertSuccess)
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
else
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
Partial view for add
#using (Html.BeginForm("AddUser", "Admin", FormMethod.Post, new { id = "addUserForm" }))
{
#Html.AntiForgeryToken()
<fieldset>
<table class="headertable">
// form elements
<tr>
<td align="center" colspan="2">
<button name="button" value="SubmitUser" class="button" id="btnSubmitUser">
Submit
</button>
<button name="button" value="CancelAddUser" class="button" id="btnCancel">
Cancel
</button>
</td>
</tr>
</table>
</fieldset>
}
Ajax call on Submit button
$('#btnSubmitUser').click(function () {
$.ajax({
url: '#Url.Action("AddUser", "Admin", new { Area = "PrivateCEQRApplication" })',
type: 'POST',
dataType: 'json',
cache: false,
headers: headers,
data: {
FirstName: $('#txtFirstNameAdd').val(),
MiddleName: $('#txtMiddleNameAdd').val(),
LastName: $('#txtLastNameAdd').val(),
EmailAddress: $('#txtEmailAddressAdd').val(),
UserRole: $('#ddlUserRoleSelectedAdd').val()
},
beforeSend: function (xhr, settings) { xhr.setRequestHeader('__RequestVerificationToken', token); },
success: function (data) {
if (data.success) {
alert("The user has been added.");
$(".ui-dialog-content").dialog().dialog("close");
}
else {
//error handling
}
},
error: function (xhr, textStatus, errorThrown) {
alert("There was a problem with the operation. Please try again" + "Status: " + textStatus + "Error: " + errorThrown);
}
});
});
Irrespective of whether there is an error or not when ever I click the Submit button I get a json file with { success : true } to download By IE.
I have read quite a few article about this and how it says to set Content type application/json or text/html
If i set content type to application/json I still get prompted to download and if i set text/html a new page opens with { success : true }.
I also noticed if i put e.preventDefault(); in my btnSubmitUser click event I don't get prompted for download but then i loose the error handling.
All I want is for dialog to close if there is no error (json success true) by executing this code
alert("The user has been added.");
$(".ui-dialog-content").dialog().dialog("close");
and display error if any by executing the json success false block.
Your help will be greatly appreciated.
Thanks
As Adeneo says, you have to prevent the default action of the form submit to allow the javascript to complete. You can do this by adding event.preventDefault(); as the first line of your function (just below $('#btnSubmitUser').click(function () {) or by having the function return false.

Categories