Repeating an AJAX request after login - javascript

I'm sending some information via AJAX to a PHP-Script to get some text, which should be displayed. So far there is no problem. But if the user is logged out, the result would be false and a modal with a login-form is shown.
If the user gets logged in, the first information (var data) should be send one more time, as the first sending wasn't accepted.
$.ajax({
url: "script.php", type: "POST", data: data, dataType: "json"
})
.done(function( json ) {
if (json.result === false) {
showModal("login"); return;
}
else {
$('#result').html(json.result);
}
});
The showModal function is also connected to an ajax request, so the user is getting logged in... After that the first data should be send one more time...
function showModal() {
$('body').append('<form>...'); // Show Modal with form to login
}
// With submit form, the user will be logged in
$('body').on('submit','#loginform',function(event){
$.ajax({
url: "login.php",
type: "POST",
data: { 'username': username, 'password': password },
dataType: "json"
})
.done(function( json ) {
// User is now logged in
// Now repeat first request
});
});

Put your code inside a function. You can call a function whenever you need it:
var sendData = function() {
$.ajax({ url: "script.php", type: "POST", data: data, dataType: "json" })
.done(function( json ) {
if (json.result === false) {
showModal("login"); return;
}
else {
$('#result').html(json.result);
}
});
};
// now run sendData() when you want to trigger it
Where to call sendData() the second time depends on how your login (showModal) works. Find a way to catch a 'successful login' event.
You can pass sendData to the showModal function and call it there. This way showModal does not need to know anything about data:
var sendData = function() {
$.ajax({ url: "script.php", type: "POST", data: data, dataType: "json" })
.done(function( json ) {
if (json.result === false) {
// The function sendData is passed as a parameter - will be called after a successful login
showModal("login", sendData); return;
}
else {
$('#result').html(json.result);
}
});
};
Then, where showModal is defined:
function showModal(dialog, loginCallback) {
$('body').append('<form>...'); // Show Modal with form to login
// With submit form, the user will be logged in
$('#loginform').on('submit', function(event) {
$.ajax({
url: "login.php",
type: "POST",
data: { 'username': username, 'password': password },
dataType: "json"
})
.done(function( json ) {
// User is now logged in
// Now repeat first request
loginCallback();
});
});
}

You can have the ShowModal function to accept another argument as ajax Options. The if ajax options are defined just call them in the done.
function showLoginModal(ajaxOptions){
$.ajax({
url: "login.php",
type: "POST",
data: { 'username': username, 'password': password },
dataType: "json"
})
.done(function( json ) {
if(ajaxOptions!== undefined){
$.ajax(ajaxOptions);
}
});
}
Then pass the ajaxOptions from your calling function
$.ajax({
url: "script.php", type: "POST", data: data, dataType: "json"
})
.done(function( json ) {
if (json.result === false) {
showLoginModal(this);
}
else {
$('#result').html(json.result);
}
});

Related

How do I wait for an action to finish before showing the next alert using sweetalert2

So I have an ASP.NET MVC Core project and when I click a button I want to display an alert using sweetalert2.
The button looks like this
<a class="btn btn-primary" onclick="doFunction(#(JsonConvert.SerializeObject(number))); ">Click</a>
And the JavaScript looks like this
function doFunction(model) {
Swal.queue([{
title: 'TestData',
confirmButtonText: 'OK',
text: 'TestData',
showLoaderOnConfirm: true,
preConfirm: () => {
$.ajax({
type: "POST",
url: '#Url.Action("Tester", "Home")',
contentType: "application/json; charset=utf-8",
data: { data: "yourdata" },
dataType: "json",
//success: function(recData) { alert('Success'); },
//error: function() { alert('A error'); }
}).then(Swal.insertQueueStep("Woo", "Woo"))
.catch(() => {
Swal.insertQueueStep({
icon: 'error',
title: 'Something went wrong'
})
});
}
}])
}
And here is the Action
public IActionResult Tester()
{
using (var context = new DbContext(_context))
{
var user = context.Users.FirstOrDefault(x => x.UserName == "TheUser");
return new JsonResult(user.UserName);
}
}
And right now it displays an alert, and when I click "OK" it shows the next alert but no loading window inbetween.
How do I properly call an action that's inside a controller and display a loading alert while it waits for the action to finish, followed by a finished alert.
There is a DONE, Fail option in ajax, move it under there..
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});
$.ajax({
type: "POST",
url: '#Url.Action("Tester", "Home")',
contentType: "application/json; charset=utf-8",
data: { data: "yourdata" },
// dataType: "json", // comment this out
// blah blah... and then the done option... below
done: function(data){
if (doSomeValidcheck(data)){
Swal.insertQueueStep("Woo", "Woo"))
// blah blah ...
return true;
} else {
return false;
}
}
});
Looks like we need to remove the datatype json
Update:
Move the done to the end of the Ajax call like so...
$.ajax({
type: "POST",
url : postUrl,
data: data
}).done(function() {
alert("Success.");
})

Ajax: Pass Model List to Controller

I have a view that takes a list of a model as the Model, so
#model List<Collections.Models.Status>
I want to pass this list as the data for an Ajax call, but I keep getting "System.Collections.Generic.List[Collections.Models.Status]" instead of the values in the model.
Here's the Ajax code:
$.ajax({
url: "/Home/Update",
data: JSON.stringify(#Model),
type: 'POST',
dataType: 'json',
success: function (responseJSON) {
if (responseJSON.message == 'success') {
alert('here');
}
},
error: function (error) {
showModal("Error: " + error.message);
}
});
Which translates in the debugger to:
$.ajax({
url: "/Home/Update",
data: JSON.stringify(System.Collections.Generic.List`1[Collections.Models.CollectionStatus]),
type: 'POST',
dataType: 'json',
success: function (responseJSON) {
if (responseJSON.message == 'success') {
alert('here');
}
},
error: function (error) {
showModal("Error: " + error.message);
}
});
How do I pass the actual values of the list instead of System.Collections.Generic.List[Collections.Models.Status]?
I've tried #Model.ToList(), #Html.Raw(Model), neither worked.
set contentType property to application/json.
and use below code to set data property
data: JSON.stringify({'your controllers parameter name': '#Model'})

How to send a JavaScript object on the server side (ASP NET MVC)?

Below is the relevant code (JS+jQuery on the client side):
function getuser(username, password) {
var user = new Object();
user.constructor();
user.username = username;
user.password = password;
//....
$("#a1").click(function () {
var u = getuser($("#username").val(), $("#password").val());
if (u == false) {
alert("error");
} else {
//....
}
});
}
The question is how to send var u to a session on the server side?
You can use ajax to accomplish this. Something like:
$.ajax({
url: "/Controller/Action/",
data: {
u: u
},
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
//handle response from server
}
});
Then have a controller action to receive the data:
[HttpPost]
public ActionResult Action(string u)
{
try
{
//do work
}
catch (Exception ex)
{
//handle exceptions
}
}
Note that /controller/action will be specific to where youre posting the data to in your project
See the documentation
For example:
If you just want to do a simple post the following may suit your needs:
var user = getUser(username, password);
$.post(yourserverurl, user, function(response){console.log("iam a response from the server")});
As the documentation says:
This is a shorthand to the equivalent Ajax function:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So In your example:
$.ajax({
type: "POST",
url: "/mycontroller/myaction",
data: {user: getUser(username, password)},
success: function(responseFromServer){//handleResponseHere},
error: function(xhr){//handleyourerrorsHere}
dataType: yourdatatype
});

Suppressing SUCCESS alert boxes?

I have three functions that called as shown below (Functions not included):
Code:
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllSourcepData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSourceData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllSpouseData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSpousData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllDividentData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveDividentData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".
This forces user to have to close three popup boxes.
Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?
You could also simplified your code by using Promise.all:
$("#btnSubmit").click(function() {
var allSourcepData = JSON.stringify(getAllSourcepData());
var allSpouseData = JSON.stringify(getAllSpouseData());
var allDividentData = JSON.stringify(getAllDividentData());
Promise.all([
getData('closures.aspx/SaveSourceData', allSourcepData),
getData('closures.aspx/SaveSpousData', allSpouseData),
getData('closures.aspx/SaveDividentData', allDividentData)
])
.then( alert )
.catch( alert )
});
function getData(url, data)
{
return new Promise((resolve, reject){
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: () => { resolve("Data Added Successfully") },
error: () => { reject("Error while inserting data"); }
});
})
}
You need to wait until all ajax requests are complete, like in this answer
So in your case you need to create functions for all $.ajax calls like this:
function ajax1() {
var data = JSON.stringify(getAllSourcepData());
$.ajax({
url: 'closures.aspx/SaveSourceData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
}
// add ajax2() and ajax3() ...
And then use only one click handler like this:
$("#btnSubmit").click(function() {
$.when(ajax1(), ajax2(), ajax3()).then(function(a1, a2, a3){
// success, display message
}, function(){
// exception
});
});
You can reorder a little your code to use the deferred method to jQuery 1.5+ otherwise you can implement as this answer:
jQuery callback for multiple ajax calls
Why you want to call 3 times for button click?
Why not put them all together?
Any how you can use variable as isAlertToBeShown= false and after pushing data make it has true. finally check the variable is true or false.

Run Javascript function as long as condition is true

I'm building a PhoneGap app where user press button which then sends data to server. On the success handler I have a new function that asks user some questions with prompt box and then sends them back to server. So I need to make the prompt box appear as long as the condition "status=ok" is true.
I don't know how many times the prompt box has to appear, it can be anything from 1 to 10 times, so I guess I need to make a some sort of loop, but how can I do it?
This is the code I've been using now:
function UpdateRecord(update_id)
{ var id = getUrlVars()["id"];
jQuery.ajax({ type: "POST",
url: serviceURL + "update.php",
data: 'id='+id ,
cache: false,
success: function(data) {
console.log(data)
if(data.key[0].status == "ok"){
var reply = prompt(data.key[0].QUESTION, "");
jQuery.ajax({ type: "POST",
url: serviceURL + "question.php",
data: 'id='+id+'&reply='+reply ,
cache: false,
success: function(data) {
window.location = "page.html" }
} else {
window.location = "page.html"
}
}
});
}
I think what your after is moving the response from the AJAX call into a method AskQuestion (or whatever you want to call it). This function would prompt and would query if the answer was correct or not and redirect them to another page:
function AskQuestion(data)
{
var id = getUrlVars()["id"];
console.log(data);
if(data.key[0].status == "ok") {
var reply = prompt(data.key[0].QUESTION, "");
jQuery.ajax({ type: "POST",
url: serviceURL + "question.php",
data: 'id='+id+'&reply='+reply,
cache: false,
success: AskQuestion});
} else {
window.location = "page.html";
}
}
function UpdateRecord(update_id)
{
var id = getUrlVars()["id"];
jQuery.ajax({ type: "POST",
url: serviceURL + "update.php",
data: 'id='+id,
cache: false,
success: AskQuestion});
}

Categories