Nested ajax function calls inside a for loop - javascript

I have looked into many solutions which uses deffered and promises.Tried those solutions in my scenario but couldn't got a solution.I have been fighting with through out the entire day.My scenario is.
I have array of customers.And i need to do some certain actions to each customer one by one which are defined as ajax.
private function main()
{
customers=["customer1","customer2"]
customers.forEach(function(customer) {
function1();
function2();
function3();
}
}
private function function1()
{
$.ajax({
type: "POST",
url: Url1,
data: {},
success: function (data) {
console.log("a");
},
dataType: 'JSON'
});
}
private function function2()
{
$.ajax({
type: "POST",
url: Url2,
data: {},
success: function (data) {
console.log("b");
},
dataType: 'JSON'
});
}
private function function3()
{
$.ajax({
type: "POST",
url: Url3,
data: {},
success: function (data) {
console.log("c");
},
dataType: 'JSON'
});
}
When the main function is called .My desired output is
a
b
c
a
b
c
But the output i am getting is
a
a
b
b
c
c
Please help me find a solution.

Ajax call by default is the async. action.
function send() {
fetch(
url,
{
method: 'post',
header: {'Content-Type' : 'application/text'},
body: 'a'
}
).then(
() => {
console.log('a is sended');
fetch(
url,
{
method: 'post',
header: {'Content-Type' : 'application/text'},
body: 'b'
}
).then(
() => {
console.log('b is sended');
fetch(
url,
{
method: 'post',
header: {'Content-Type' : 'application/text'},
body: 'c'
}
).then( () => console.log('c is sended') )
}
)
}
)
}

Finally i solved my issue by making a recursive function call without using loop.
var customers=["customer1","customer2"];
var currentIndex=0;
private function main()
{
if(customers[currentIndex]){
function1().done(function(data) {
console.log("a");
function2().done(function(data) {
console.log("b");
function3().done(function(data) {
console.log("c");
currentIndex++;
main();
});
});
});
}
}
private function1()
{
return $.ajax({
type: "POST",
url: url1,
data: {},
dataType: 'JSON'
});
}
private function2()
{
return $.ajax({
type: "POST",
url: url2,
data: {},
dataType: 'JSON'
});
}
private function3()
{
return $.ajax({
type: "POST",
url: url3,
data: {},
dataType: 'JSON'
});
}
And current output is
a
b
c
a
b
c

Related

Is it possible to execute nested ajax on click event?

I am using nested ajax in my code and wanted to execute it on click of a button. but when I try to add any event listener inner ajax never gets success. when I remove on click event or event listener it works fine.
$("#Id1").click(function() {
$.ajax({
url: 'url1',
type: 'get',
data: {
method: 'method1',
id: id1
},
datatype: 'json',
success: function(a) {
console('ajax1');
if (a == 1) {
$.ajax({
url: 'url2',
type: 'post',
data: {
arg1: p,
arg2: q
},
datatype: 'json',
success: function(b) {
console('ajax2');
}
}
else {
alert('hello');
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This code fails and never executes success part of inner ajax. whereas code mentioned below works fine.
$.ajax({
url: 'url1',
type: 'get',
data: {
method: 'method1',
id: id1
},
datatype: 'json',
success: function(a) {
console('ajax1');
if (a == 1) {
$.ajax({
url: 'url2',
type: 'post',
data: {
arg1: p,
arg2: q
},
datatype: 'json',
success: function(b) {
console('ajax2');
}
}
else {
alert('hello');
}
}
});
Can somebody please help me on this? I am very to new to ajax and javascript. I tried putting error and failure inside second ajax but it do not enter in that callbacks.
I got that working just by doing this:
$("#Id1").click(function(e) {
e.preventDefault();
$.ajax({
url: 'url1',
type: 'get',
data: {
method: 'method1',
id: id1
},
datatype: 'json',
success: function(a) {
console('ajax1');
if (a == 1) {
$.ajax({
url: 'url2',
type: 'post',
data: {
arg1: p,
arg2: q
},
datatype: 'json',
success: function(b) {
console('ajax2');
}
}
else {
alert('hello');
}
}
});
});

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

Loading AJAX calls one after the other

I have the following 3 AJAX function, and the problem is that it loads sessionAllCoursePage3 first then sessionAllCoursePage2 then sessionAllCoursePage1, I wanted to be inverse. I want to ensure that page1 is loaded first, then page 2, page 3, etc.
// Retrieve last 9 session
$.ajax({
type: "POST",
data: { run: true, providerName: $('#providerName').val() },
url: '/app/functions/sessionAllCoursePage1.php',
cache: false,
success: function(response) {
// Response is value returned from php
$('#contentPage1').html(response);
return false;
}
});
// Retrieve the next 9 session
$.ajax({
type: "POST",
data: { run: true, providerName: $('#providerName').val() },
url: '/app/functions/sessionAllCoursePage2.php',
cache: false,
success: function(response) {
// Response is value returned from php
$('#contentPage2').html(response);
return false;
}
});
// Retrieve the next 9 session
$.ajax({
type: "POST",
data: { run: true, providerName: $('#providerName').val() },
url: '/app/functions/sessionAllCoursePage3.php',
cache: false,
success: function(response) {
// Response is value returned from php
$('#contentPage3').html(response);
return false;
}
});
I'd suggest you chain them with promises:
// Retrieve last 9 session
$.ajax({
type: "POST",
data: {
run: true,
providerName: $('#providerName').val()
},
url: '/app/functions/sessionAllCoursePage1.php',
cache: false
}).then(function(response) {
$('#contentPage1').html(response);
return $.ajax({
type: "POST",
data: {
run: true,
providerName: $('#providerName').val()
},
url: '/app/functions/sessionAllCoursePage2.php',
cache: false
}).then(function(response) {
$('#contentPage2').html(response);
return $.ajax({
type: "POST",
data: {
run: true,
providerName: $('#providerName').val()
},
url: '/app/functions/sessionAllCoursePage3.php',
cache: false
});
}).then(function(response) {
$('#contentPage3').html(response);
});
Or, using a little more shared code:
function ajaxCommon(url, resultId) {
return $.ajax({
type: "POST",
url: url,
data: {
run: true,
providerName: $('#providerName').val()
},
cache: false
}).then(function(result) {
$("#" + resultId).html(result);
});
}
ajaxCommon('/app/functions/sessionAllCoursePage1.php', 'contentPage1').then(function() {
return ajaxCommon('/app/functions/sessionAllCoursePage2.php', 'contentPage2');
}).then(function() {
return ajaxCommon('/app/functions/sessionAllCoursePage3.php', 'contentPage3');
});
Or, a little more table/loop driven:
function ajaxCommon(url, resultId) {
return $.ajax({
type: "POST",
url: url,
data: {run: true, providerName: $('#providerName').val()},
cache: false
}).then(function(result) {
$("#" + resultId).html(result);
});
}
[1,2,3].reduce(function(p, item) {
return p.then(function() {
return ajaxCommon('/app/functions/sessionAllCoursePage' + item + '.php', 'contentPage' + item);
});
}, Promise.resolve());
Just place your asynchronous code inside some request callback (e.g. success). Didactically:
var firstRequestOptions = {
success: function () {
secondRequest();
}
};
var secondRequestOptions = {
success: function () {
thirdRequest();
}
};
var thirdRequestOptions = {
success: function () {
firstRequest();
}
};
var firstRequest = function () {
console.log('request 1');
$.ajax(firstRequestOptions);
};
var secondRequest = function () {
console.log('request 2');
$.ajax(secondRequestOptions);
};
var thirdRequest = function () {
console.log('request 3');
$.ajax(thirdRequestOptions);
};
Then:
firstRequest();
The log should be:
> request 1
> request 2
> request 3
> request 1
> request 2
...
You can use Array.prototype.shift(), String.prototype.match() with Regexp /\d/ to match digit character in url, .then()
function request(url) {
return $.ajax({
type: "POST",
data: {run: true, providerName: $('#providerName').val()},
url: url,
cache:false,
success: function (response) {
$('#contentPage' + url.match(/\d/)[0]).html(response);
}
});
}
var urls = ['/app/functions/sessionAllCoursePage1.php'
, '/app/functions/sessionAllCoursePage2.php'
, '/app/functions/sessionAllCoursePage3.php'];
request(urls.shift())
.then(function re() {
if (urls.length) {
request(urls.shift()).then(re)
}
})
// can use `.catch()` here at jQuery 3.0+
.fail(function(jqxhr, textStatus, errorThrown) {
// handle error
console.log(errorThrown);
});
plnkr http://plnkr.co/edit/fREO6Jzw65gq2s3jrwjp?p=preview

Can I use jquery's .done() more than once?

I have 2 JS literals:
var obj1 = {
Add: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/add",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
var obj2 = {
List: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/list",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
And this is my document.ready:
$(document).ready(function () {
obj1.Add(1).done(function (data) {
alert('you added ' + data);
});
obj2.List().done(function (data) {
$.each(jQuery.parseJSON(data), function (i, item) {
// fill a combo box
});
});
});
jQuery just executes the first call and obj2.List() ain't called at all.
How to properly use the deffered objects in this case?
Change your Add and List function to RETURN the ajax object.
Add: function (id) {
return $.ajax({..
and
List: function (id) {
return $.ajax({...
This way - it will return the jqXHR obj which will return the deferred object.
This implement the Promise interface which has : the callbacks you are looking for.
edit :
look at this simple example which does work :
var obj1 = {
Add: function (id) {
return $.ajax({
type: "get",
data: JSON.stringify({
"id": 1
}),
url: "http://jsbin.com/AxisAmi/1/quiet",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("at success --"+data.data)
}
});
}
};
obj1.Add(2).done(function (a){alert("at done --"+a.data);});

ajax call not working with in ajax

I using the mvc controller with ajax. I perfom the task using the jquery confirm box. when i click the "ok" button its needs to the call another ajax and its link to the another controller but its not working
Sample code:
function button_click() {
$.ajax({
type: 'POST',
url: 'url',
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { call(data); }
else { alert(data.data); }
}
});
}
function call(data)
{
var ans = confirm(data)
if(ans)
{
$.ajax({
type: 'POST',
url: '#(Url.Action("StudentList", new { Area = "Mec", Controller = "HOD" }))',, // this url not goes to the controller
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { alert(data.data); }
else { }
}
});
} else { }
}
i have tried your code but it worked for me.the difference is that
you need to pass data in correct format. data:data or data:{ data:data } but not data:{data}
function button_click() {
$.ajax({
type: 'POST',
url: 'Demo/Demo_action',
data: { data: "what you want to pass" },
//dataType: 'json',
//contentType: 'application/json',
success: function (data) {
if (data == "hello") {
call(data);
}
}
});
}
function call(data) {
var ans = confirm(data)
if (ans) {
$.ajax({
type: 'POST',
url: '#(Url.Action("Demo_action2", new { Area = "Mec", Controller = "Home" }))',
//url: 'Home/Demo_action2', // this url not goes to the controller
data: { data: data },
dataType: 'json',
success: function (data) {
alert(data);
}
});
}
else
{ }
}

Categories