Call one ajax call after another - React on click function - javascript

I am trying to restart a service. For that I have to execute 2 API calls.
First cancel and then run.
I am trying to execute these 2 POST Ajax calls by binding the run inside the success of cancel call as a callback. But its giving me error and doesnt refresh the browser on success. When I execute only one call "run" it works fine and the page is reloaded as well.
FYI : These are POST Ajax calls.
onClickRestart(params, onSuccess, onFailure) {
var {
pipelineName,e
} = params;
const url1 = `/api/${params}/cancel`;
const url2 =`/api/${params}/run`
return $.ajax({
type: 'POST',
url1,
processData: false,
async:false,
contentType: 'application/json',
success: (response) => {
if(!response.error) {
$.ajax({
type: 'POST',
url2,
processData: false,
async:false,
contentType: 'application/json',
success: (response) => {
if(!response.error) {
location.reload(true);
}
},
error: (error) => {
console.log(error);
}
});
}
},
error: (error) => {
console.log(error);
}
});
}
What is my mistake ?

Related

JS Aysnc call from DotNet Application

I am getting Timeout error as execution of this call takes 4-5 mins.
Can you please help me out on this.
This is C# application and I am calling from JS.
function fnGetAlertsData() {
$.ajax({
url: "http://192.168.55.95:8011/mas_billing/pullroster", async: true, type: 'POST',
data: '{"startdate": "03/28/2022", "enddate": "03/28/2022","invoice_number": ""}',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
console.log(result);
var mydata = JSON.stringify(result);
console.log(mydata);
sessionStorage.setItem("SnNvbkl0bXNPZVJlZ2lzdHJ", mydata);
// $("#dvResult").html(result);
}
,
error: function (error) {
console.log(error);
},
timeout: 300000
});

How can a guarantee one ajax call is complete before calling another?

I am working on a flask application and there is this javascript function associated with a form
function applyQueries() {
// does some things
if(currentCatalog != ''){
addCatalogFilters(currentCatalog);
}
$.ajax({
type: 'POST',
url: "/applyQueries",
contentType: "application/json",
success:function(response){
// does some stuff here
})
}
The addCatalogFilters() function is also an ajax call. Both these calls change some variables in the python side of things. What I want to know is if the first ajax call (in addCatalogFilters), is guaranteed to execute and return before the second one. I am ending up with weird results that appear to be race conditions based on the order the ajax calls execute. Is this possible with code structured like this? Also if so, how can I fix it?
// Add user catalog filters
function addCatalogFilters() {
catalog = currentCatalog;
formData = new FormData(document.getElementById('catalogFilterForm'));
$.ajax({
type: 'POST',
url: "/addCatalogFilters",
data: formData,
processData: false,
contentType: false,
success: function (response){
document.getElementById(catalog + 'close').style.display = 'block';
document.getElementById(catalog + 'check').style.display = 'none';
addBtns = document.getElementsByClassName("addBtn");
removeBtns = document.getElementsByClassName("removeBtn");
for (i = 0; i < addBtns.length; i++) {
addBtns[i].style.display = "none";
removeBtns[i].style.display = "inline-block";
}
}
})
};
You can ensure with success function of ajax. First call a ajax (let's say ajax1) then call another ajax call within the success function of first ajax call (ajax1 success function).
addCatalogFilters(currentCatalog)
{
$.ajax({
type: 'POST',
url: "/the-post-usl",
success:function(response){
$.ajax({
type: 'POST',
url: "/applyQueries",
contentType: "application/json",
success:function(response){
// does some stuff here
});
})
}
function applyQueries() {
// does some things
if(currentCatalog != ''){
addCatalogFilters(currentCatalog);
}
}
It may not be the optimum way. But guarantee one ajax call is complete before calling another.
You could try using async/await like this:
async function applyQueries() {
if(currentCatalog !== ''){
const filtersAdded = await addCatalogFilters(currentCatalog);
}
// Perform AJAX call
}
By usinc async/await, your code will wait until the addCatalogFilters() function has resolved. However, for this to work, the addCatalogFilters() function should be async with a return value. Something like this:
async function addCatalogFilters(catalog){
// Ajax call
$.ajax({
type: 'POST',
url: "foo",
contentType: "application/json",
success:function(response){
return true
})
}
Depending on how applyQueries is called, you may need to have an await or .then where you call it. Note that you can also use "result = await addCatalogFilters(currentCatalog)" to put the ajax result into a variable result that you can work with and pass to your $.ajax call in applyQueries. I don't know the nature of your code, so I can't make any direct suggestions.
async function applyQueries() {
// does some things
if(currentCatalog != ''){
// await on the returned Promise-like jqXHR (wait for ajax request to finish)
// recommend assigning awaited result to a variable and passing to next $.ajax
await addCatalogFilters(currentCatalog);
}
return $.ajax({
type: 'POST',
url: "/applyQueries",
contentType: "application/json",
success:function(response){
// does some stuff here
})
}
// Add user catalog filters
function addCatalogFilters() {
catalog = currentCatalog;
formData = new FormData(document.getElementById('catalogFilterForm'));
// return the Promise-like jqXHR object: https://api.jquery.com/jQuery.ajax/#jqXHR
return $.ajax({
type: 'POST',
url: "/addCatalogFilters",
data: formData,
processData: false,
contentType: false,
success: function (response){
document.getElementById(catalog + 'close').style.display = 'block';
document.getElementById(catalog + 'check').style.display = 'none';
addBtns = document.getElementsByClassName("addBtn");
removeBtns = document.getElementsByClassName("removeBtn");
for (i = 0; i < addBtns.length; i++) {
addBtns[i].style.display = "none";
removeBtns[i].style.display = "inline-block";
}
}
})
};
You can use async/await. However, as no one has mentioned, I would like to demonstrate how you can accomplish this with Promise.
Lets define two functions:
function first_function(data) {
return new Promise((resolve, reject) => {
let dataSet = [[]];
let response;
$.ajax({
type: "POST",
url: 'example.com/xyz',
async: false,
data: data,
success: function (value) {
response = value;
dataSet = JSON.parse(response);
resolve(dataSet)
},
error: function (error) {
reject(error)
},
processData: false,
contentType: false
});
})
}
function second_function(data) {
return new Promise((resolve, reject) => {
let dataSet = [[]];
let response;
$.ajax({
type: "POST",
url: 'example.com/abc',
async: false,
data: data,
success: function (value) {
response = value;
dataSet = JSON.parse(response);
resolve(dataSet)
},
error: function (error) {
reject(error)
},
processData: false,
contentType: false
});
})
}
Now you can make sure that second_function() gets called only after the execution of ajax request in first_function() by following approach:
first_function(data)
.then(dataSet => {
//do other things
second_function(dataSet)
.then(dataSet2 => {
////do whatever you like with dataSet2
})
.catch(error => {
console.log(error);
});
});

Nested AJAX call success function does not get run

I have the following ajax call nested inside another, but after the first one gets run, nothing gets logged to the console meanwhile it should. Where is the issue?
$.ajax({
url: "https://ck:8081/get-username",
type: "get",
success: function (response) {
userName = response
$.ajax({
url: "https://ck:8081/new-chatuser?username=" + userName,
type: "get",
success: function (response) {
console.log('response' + response)
$('onlineMembers').append(response)
}
})
}
})
There is most likely a failure in one of the requests you are sending, to remedie to that, you need to handle the errors as described in the code below :
$.ajax({
url: 'https://ck:8081/get-username',
type: 'get',
success: function(response1) {
console.log(`First succeeded : ${response2.toString()}`);
$.ajax({
url: 'https://ck:8081/new-chatuser?username=' + response1,
type: 'get',
success: function (response2) {
console.log(`Second succeeded : ${response2.toString()}`);
$('onlineMembers').append(response2);
},
error: function(error) {
console.log(`Second failed : ${error.toString()}`);
}
});
},
error: function(error) {
console.log(`First failed : ${error.toString()}`);
}
});
You may want to change $('onlineMembers') because I don't think the selector you are using is correct.

Deferred jQuery AJAX request does not run done() callback function

I have setup a simple demo using jQuery Deferred object with AJAX request to simulate how my app is doing it.
My issue is, ever since I switched over from the older non-deferred method, I cannot get a success callback.
Only the fail() callback is called. Can someone help me to get a successful callback? I don't see where it is going wrong? Appreciate any help
My demo is here http://jsfiddle.net/jasondavis/y645yp4g/4/
My old AJAX call was like this...
var ajax = $.ajax({
type: 'POST',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/gettask',
data: {
action: 'load-task-record',
task_id: taskId
},
success: function(data) {
// my success functionality here
}
});
New AJAX call using Deferred object...
// Call function that execute AJAX request and returns it
var ajaxRequest = ajaxLoadTaskData();
ajaxRequest.done(function(response) {
if( response.success ) {
alert('AJAX request success');
}else{
// output the contents of response.errors
}
}).fail(function(response) {
// AJAX request failed
console.log('response', response);
alert('AJAX request failed');
}).always(function(response) {
});
// Run AJAX request and return Promise()
function ajaxLoadTaskData() {
return $.ajax({
type: 'POST',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/gettask',
data: {
action: 'load-task-record',
task_id: '1',
},
});
}
Mock AJAX response for AJAX request to /gettask
// Mock AJAX response for AJAX request to /gettask
$.mockjax({
url: '/gettask',
contentType: 'text/json',
responseTime: 100,
response: function(settings) {
console.log('mockJax GET to /gettask :');
//console.log(settings);
if (settings.data.value == 'err') {
this.status = 500;
this.responseText = 'Validation error!';
} else {
var taskrecord = { 'name1': 'bar' };
this.responseText = taskrecord;
}
},
});
/gettask doesn't exists in that jsFiddle environment. Use console.log(settings) to see the entire content of the response. You will se that the status is 404.

IE not calling $.ajaxSetup

The following call works great in every browser but IE. $.ajaxSetup doesn't get recognized. The error and complete functions won't be called unless I add them directly into the $.ajax call.
Any idea why?
function setupAjaxCalls() {
$.ajaxSetup({
type: 'GET',
dataType: "jsonp",
contentType: "application/json",
data: {
deviceIdentifier: deviceIdentifier,
deviceType: deviceType,
memberId: loggedInMemberId,
authToken: authToken,
cache: false,
responseFormat: 1
},
error: function (x, e) {
defaultError(x, e);
},
complete: function () {
apiCallInProgress = 'false';
//alert('complete!');
}
});
}
function logInForm(memLogin, memPassword, callback) {
apiCallInProgress = 'true';
$.ajax({
type: 'POST',
dataType: "json",
url: baseApiUrl + '/MembershipService/AuthLoginSecure',
data: {
login: memLogin,
password: memPassword,
responseFormat: 0
},
success: function (data) {
if (data.Success == false) {
apiError(data);
} else {
loggedInMemberId = data.Member.Id;
authToken = data.Token;
if (typeof (callback) != "undefined" || callback) {
callback(data);
}
}
}
});
}
Straight from the documentation:
http://api.jquery.com/jQuery.ajaxSetup/
Note: Global callback functions should be set with their respective global Ajax event
handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(),
.ajaxSend()—rather than within the options object for $.ajaxSetup().
You should move the error and complete properties into their own methods. :) Or, you can just put them into the $.ajax method. Whatever works best for your preferred code pattern!

Categories

Resources