Call multiple ajax calls - ajax

$.ajax({
url: "",
jsonpCallback: 'item',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
var markup = "";
$.each(data.list, function(i, elem) {
dbInsert(elem['itemCode'], elem['description'], elem['price']);
});
},
error: function(request, error) {
alert(error);
}
});
I have the above type of different ajax calls with different urls. How can I run each Ajax call, one after another?

You can do something like this.
$('#button').click(function() {
$.when(
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('one is done')
}
}),
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('two is done')
}
})
).then( function(){
alert('Final Done');
});
});
fiddle

Keep track of the urls still to send, and have the success inline function of one ajax request go and call the next.
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
... do what you want with the data ...
if (urls.length > 0) runNextAjax();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
}
});
};
// Start the sequence off.
runNextAjax();
The above code acts on the data as it arrives, if you want to cache it all and act on it all at the end, store each result in an array, then process the array in a function that gets called at the end:
var dataAccumulator = [];
var displayAllData = function() {
for (int i = 0; i < dataAccumulator.length; ++i) {
var data = dataAccumulator[i];
... process the data into HTML as before ...
}
};
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
// Store the data we received
dataAccumulator.push(data);
if (urls.length > 0) runNextAjax();
else displayAllData();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
else displayAllData();
}
});
};
// Start the sequence off.
runNextAjax();

Related

I am passing JSON data to dependent input field

GET http://localhost:8000/getguardrate/1?_token=kSrGyMIF7twomtmIShadxWbqhNpUKlrxH6lEwDO6 500 (Internal Server Error)
this is my ajax call
$(document).ready(function() {
$('#select2-3').on('change', function() {
var c_id = $(this).val();
console.log(c_id);
if(c_id) {
$.ajax({
url: 'getguardrate/' +c_id,
type: "GET",
data : {"_token":"{{ csrf_token() }}"},
dataType: "json",
success:function(data) {
// console.log(data);
if(data){
$('#GetsiteguardRate').empty();
$('#GetsiteguardRate').focus;
$("#GetsiteguardRate").val(data[0]['sbr_g']);
}else{
$('#GetsiteguardRate').empty();
}
}
});
}else{
$('#select2-3').empty();
}
});
});

Display all data fetched, api rest using __next

I need to fetch all data from an xml link but I couldn't as it displays only 300 rows, so I found a solution that says I should use __next, I have the code below but it doesn't work, in the console I get the next url but the items (TaskName) of the first page. I want to get the TaskName(s) of the next pages.
window.addEventListener('load',function() {
$.ajax({url: _spPageContextInfo.siteAbsoluteUrl + "/_api/ProjectData/[en-US]/Tasks",
method: "GET",
dataType: "json",
headers: {Accept: "application/json;odata=verbose"},
success: function(data) {
var dataResults = data.d.results;
if (data.d.__next) {
url = data.d.__next;
console.log("url: "+url);
}
$.each(dataResults, function(key, value)
{
var tasky = value.TaskName;
console.log(tasky);
});
}});
});
I found a solution, here the code is:
function GetListItems(){
$.ajax({
url: urly,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data){
response = response.concat(data.d.results);
if (data.d.__next) {
urly = data.d.__next;
GetListItems();
}
$.each(response, function(key, value)
{
var tasky = value.TaskName;
console.log(tasky);
});
},
error: function(error){
}
});
}

What's the correct way to iterate through array and sending multiple ajax requests

I currently have some ajax that sends an array to php for processing. The array size at most would be around 1000 elements which will be enough for the server to time out while the php is processing. I would like to chunk the array and send it in batched ajax requests (or maybe just one at a time) that will each finish without timing out.
Below is my basic code structure. I'm trying to use promises and iterate through the chunks:
Here's the basic structure of the working function (non-promise version):
function ajax_function(big_array) {
$.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array',
'array_to_process': big_array
},
beforeSend: function () {
xxx
},
dataType: 'json',
success: process_big_array_chunk_handler,
error: function (xhr, desc, err) {
console.log(xhr);
console.log('Details: ' + desc + '\nError: ' + err);
}
});
}
Here's work in progress trying to add the loop and promise.
function ajax_function(big_array) {
var big_array_chunks = make it into chunks somehow;
$.each(big_array_chunks, function (big_array_chunk) {
var request = $.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array_chunk',
'array_to_process': big_array_chunk
},
dataType: 'json'
}).done(function (data) {
process_big_array_chunk_handler(data);
}).fail(function (xhr, desc, err) {
console.log(xhr);
console.log('Details: ' + desc + '\nError: ' + err);
});
});
}
Trying to get my head around how this all fits together:
each iteration of loop
responses from php
how to use my response handler when it's all done
fyi, this is being done within the context of WordPress if that matters.
Response to Bergi:
function ajax_function(big_array) {
var big_array_chunks = make big_array into chunks somehow;
var request = $.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array_chunk',
'array_to_process': big_array_chunk
},
dataType: 'json'
}).then(function (data) {
process_big_array_chunk_handler(data);
});
}
The simplest solution I can think of is to just pre-chunk the array and then just use the .reduce() design pattern for serializing promises.
function processBigArray(bigArray, chunkSize) {
// pre-split array into chunks
var chunkArray = [];
for (var i = 0; i < bigArray.length; i+=chunkSize) {
chunkArray.push(bigArray.slice(bigArray, i, chunkSize));
}
var results = [];
// use .reduce() design pattern for chaining and serializing
// a sequence of async operations
return chunkArray.reduce(function(p, chunk) {
return p.then(function() {
return $.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array',
'array_to_process': chunk
},
beforeSend: function () {
xxx
},
dataType: 'json',
}).then(function(data) {
results.push(data);
});
});
}, Promise.resolve()).then(function() {
// depending upon what your ajax returns, results might be an array of arrays
// that you would want to flatten
console.log(results);
return results;
});
}
// usage
processBigArray(someBigArray, 50).then(function(results) {
// process results here
}).catch(function(err) {
// deal with error here
console.log(err);
});

Ajax Form Submit with attachment

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.
How can i get this to work?
Here is my ajax code:
$('#submit_btn').click(function () {
$.ajax({
type: 'POST',
url: '/contact.php',
dataType: "json",
data: $('#contactform').serialize(),
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});
On the php side i have phpmailer setup and am handling the file so:
if(!empty($_FILES['file'])) {
$_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
}
$('#submit_btn').click(function () {
var formData = new FormData($('#contactform'));
$.ajax({
type: 'POST',
url: '/contact.php',
// dataType: "json",
data: formData ,
processData: false,
contentType: false,
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});

Jquery execute in wrong sequence [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the sample as below. I always got "c" first before "a" and "b". How do I get "a","b" and "c" accordingly? I would appreciate for any advice.
b.extend({
get: function (id) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("a");
}
});
for (var a = 0; a < 5; a++) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("b");
}
});
}
console.log("c");
}
});
Try
put your code in success:
b.extend({
get: function (id) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("a");
for (var a = 0; a < 5; a++) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("b");
if (a === 5) {
console.log("c");
}
}
});
}
}
});
}
});
You can also use deferred:
b.extend({
get: function (id) {
var request = jQuery.ajax({
type: 'GET',
url: url,
data: pdata
}).then(function(result) {
console.log("a");
return result;
});
for (var a = 0; a < 5; a++) {
request = request.then(function(result) {
return jQuery.ajax({
type: 'GET',
url: url,
data: pdata
}).then(function(result) {
console.log("b");
return result;
});
});
}
request.then(function() {
console.log("c");
});
}
});
Do the call for C in the callback of B, and the call for B in the callback of A
jQuery is async, so some Ajax requests may finish before others.
b.extend({
get: function (id) {
var async = $.ajaxSetup()['async']; // store the current value of async to a variable
$.ajaxSetup({'async':false}); // Set async to false
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("a");
}
});
for (var a = 0; a < 5; a++) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("b");
}
});
}
console.log("c");
$.ajaxSetup({'async': async }); // Set async to back to original value
}
});
The only downside to this is that your page will 'hang' until the request is completed

Resources