Hi here is an example with jsfiddle using Deferred Objects the basic of this example is simple I use 2 separate functions:
- one to login a user.
- the other one will display some data once the login is complete.
The first call display a modal before it sends the data, once the request is done and the login success the modal msg updates and the second call is executed, after the second call completes the information is displayed into the modal.
The code is a basic example and was made on the fly, it does not have a fail method or an always method but I left the link to the documentation in case you want to implement those methods:
The Javascript:
const _ajaxLogin = (data)=>{
console.log(data);
return $.ajax({
type: 'POST',
url: '/echo/json/',
data: {json:JSON.stringify(data),delay:1},
beforeSend: function() {
$('#myModal').css("display","block");
},
dataType: 'json'
})
}
const _ajaxInfo = (data)=>{
console.log(data);
return $.ajax({
type: 'POST',
url: '/echo/json/',
data: {json:JSON.stringify(data),delay:3},
dataType: 'json'
})
}
$('#btnLogin').on('click',(e)=>{
let username = $('#txtUsername').val(),
password = $('#txtPassword').val(),
json = {
username : username,
password : password,
response: "success"
};
var information = {status:"active",account:34566 , currency:"$", amount: 42250, last_transaction:'05/08/2019 14:25:32', name:"John", lastname:"Doe"};
_ajaxLogin(json)
.done((response)=>{
if(response.response == "success"){
$('#msgTittle').text("Loading Your Account Information");
_ajaxInfo(information)
.done((account_response)=>{
if(account_response.status != undefined){
$('#loading').css("display","none");
$('#msgTittle').text("Welcome back "+account_response.name+" "+account_response.lastname);
$("#info").text("Account:"+account_response.account+", your avaliabvle money is "+account_response.currency+account_response.amount+", your last transaction was "+account_response.last_transaction);
$('#btnLogout').css("display","");
}
})
}
})//end first done
.fail((response)=>{
console.log("error:"+response);
})
});//end click
$('#btnLogout').on('click',(e)=>{
$("#info").text("");
$('#loading').css("display","block");
$('#msgTittle').text("Your login was successfull");
$('#myModal,#btnLogout').css("display","none");
});
**Edit:**As you can see there are some echo/json stuff in the url this is the way jsfiddle has to simulate an ajax call
Hope it helps