sum values from multiple ajax requests - javascript

im trying to get the total value of the data returned by the ajax requests, but it is showing total:0 because it is executing the totalRev before completing the ajax requests.
var totalRev = 0;
$.ajax({
type: "POST",
url: "cloudmobi.php",
data: {action: 'cloudmobi'},
dataType:'JSON',
success: function(response){
document.getElementById('cloudmobi').innerHTML = response.cloudmobi;
console.log(response.cloudmobi);
var cloudmobi = parseInt(response.cloudmobi);
console.log('CLOUDMOBI:'+cloudmobi);
totalRev += cloudmobi;
}
});
$.ajax({
type: "POST",
url: "mobusi.php",
data: {action: 'mobusi'},
dataType:'JSON',
success: function(response){
document.getElementById('mobusi').innerHTML = response.mobusi;
console.log(response.mobusi);
var mobusi = parseInt(response.mobusi);
totalRev += mobusi;
console.log('MOBUSI:'+mobusi);
}
});
$.ajax({
type: "POST",
url: "appnext.php",
data: {action: 'appnext'},
dataType:'JSON',
success: function(response){
document.getElementById('appnext').innerHTML = response.appnext;
console.log(response.appnext);
var appnext = parseInt(response.appnext);
totalRev += appnext;
console.log('APPNEXT:'+appnext);
}
});
console.log('TOTAL:'+totalRev);
I do not want to use async because the whole purpose of using ajax here is to load the site fast then dynamically load the data

jQuery "when" solves your problem:
$.when( d1, d2 ).done(function ( v1, v2 ) {
console.log( v1 ); // "Fish"
console.log( v2 ); // "Pizza"
});

It would be far better to send all the data in a single request so you can do the sum on the server and send it in a single property in the response.
Assuming, for whatever reason, you cannot do that, then you could instead store all the promises from the AJAX requests and then execute your code after all of them have completed and added their values to an array. Then you can sum the array. Something like this:
var values = [];
var promises = [
$.ajax({
// ajax settings...
success: function() {
values.push(parseInt(response.cloudmobi), 10);
}
}),
$.ajax({
// ajax settings...
success: function() {
values.push(parseInt(response.mobusi), 10);
}
}),
// Nrequests...
];
$.when.apply(this, promises).done(function() {
var sum = values.reduce(function(a, b) {
return a + b;
}, 0);
// work with sum here...
});

Related

loop chained async ajax calls with promise and returns between functions

I am loading results in batches and looking for a solution that will prevent the screen from freezing until all my ajax calls have returned. Someone recommended using async promises (is that the correct solution?) but I don't understand how the syntax works to pass parameters between the chained calls.
It's the equivalent of this looped chain of many ajax calls except I need all calls to depend on the result from the previous call (in this example the loops for url1 all fire simultaneously which is not what I want). The run should end when the returned boolean "proceed" (from any of the ajax calls) is false, not when the last loop and url have been reached.
for (let i = 0; i < numLoops; i++) {
$.ajax({
url: url1,
type: "POST",
data : jQuery.param({loop: i}),
success: function(response) {
var result = JSON.parse(response);
if(result['proceed']){
$.ajax({
url: url2,
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
if(result['proceed']){ ... and so on
I am trying to use jquery .when .then promises with these functions:
function First(loop, proceed, updated){
if(proceed)
{
$.ajax({
url: url1,
type: "POST",
data : jQuery.param({loop: loop}),
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
updated(result['proceed']);
}
});
}
}
function Second(proceed, updated){
if(proceed)
{
$.ajax({
url: url2,
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
updated(result['proceed']);
}
});
}
}
function Third(proceed, updated){
if(proceed)
{
$.ajax({
url: url3,
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
updated(result['proceed']);
}
});
}
}
I'm having a hard time figuring out how to chain them so that the return from previous function is passed to the next function.
This incorrect syntax describes what I'm trying to do:
var proceed=true;
for (let i = 0; i < numLoops; i++) {
$.when(First(i, proceed, updated); function updated(content) {var proceed=contents;} )
.then(Second(proceed, updated); function updated(content) {var proceed=contents;})
.then(Third(proceed, updated); function updated(content) {var proceed=contents;})
}
How to pass updated proceed from First to Second?
How to pass updated proceed from Third to First at end of each loop?
I'm not super versed with javacript and would be most grateful for pointers. Thanks!
First, convert the $.ajax calls into real Promise objects, as described in this thread:
function asyncAjax(options){
return new Promise(function(resolve, reject) {
options.success = resolve;
options.error = reject;
$.ajax(options);
});
}
Alternatively, use the Fetch API, which supports promises by default.
Then use an async function to make the requests:
for (let i = 0; i < numLoops; i++) {
let response = await asyncAjax({
url: url1,
type: "POST",
data: jQuery.param({loop: i})
});
let result = JSON.parse(response);
if (result['proceed']) {
response = await asyncAjax({ url: url2 });
result = JSON.parse(response);
...
}
}

how to overload an array in javascript?

thsi is my code:
var data_book_list=new Array();
var test_type= jQuery('#test_type').val('list1');
function bookList() {
jQuery.ajax({
type: "POST",
url: "array.php",
dataType: 'json',
data: {book:book},
success: function(data){
for(var i=0;i<data.length;i++)
{
data_list.push(data[i]);
}
}
});
imagine database like: list1 has a1,a2,a3 & list2 b1,b2,b3
if i selected value list1 ajax get that value and sent it to php.
php using where case so it gives back to ajaxa1,a2,a3
now data has a1,a2,a3 i make it that a new array form for loop like ['a1','a2','a3']
i push this to a var data_book_list=[];
it work great.
but my problem is if i select option list2
data hasb1,b2,b3 and data_book_list=[] has a1,a2,a3
for loop push data b1,b2,b3 to array data_book_list it will extend like ['a1','a2','a3', 'b1','b2','b3']
but i need like this ['b1','b2','b3] in array data_book_list. how to clear or overload old array data automatically.
If you need to keep track of all the values retrieved so far, then you will have to use an object and have the value as array, corresponding to the keys.
var data_book_list_obj = {};
var test_type= jQuery('#test_type').val('list1');
function bookList() {
jQuery.ajax({
type: "POST",
url: "array.php",
dataType: 'json',
data: {book: test_type},
success: function(data){
for(var i=0;i<data.length;i++)
{
data_book_list_obj[test_type] = data_book_list_obj[test_type] || [];
data_book_list_obj[test_type].push(data[i]);
}
}
});
Or if you need only the recent information, then just assign the value.
var data_book_list=new Array();
var test_type= jQuery('#test_type').val('list1');
function bookList() {
jQuery.ajax({
type: "POST",
url: "array.php",
dataType: 'json',
data: {book: test_type},
success: function(data){
// Edit removed for loop wrongly put here
data_book_list = data;
}
});

Re-run Ajax with data from its own response

Is it possible to insert into ajax post some altered variable from its own success data?
On page load, first ajax fires and shows some records from mysql, then I take last record ID and store it in latestID, next second ajax fires and retrieves only records from that ID forward and then stores the lastId and fires again.
$.ajax({
type: 'POST',
url: '{{ ... }}',
dataType: 'json',
'success': function (data) {
callback(data);
}
});
function callback(response) {
var idList = [];
var printer_category = response.printer.productcategory_id;
var printer_timer = parseInt(response.printer.timer);
var printer_storeid = response.printer.store_id;
var printer_physicalPrint = parseInt(response.printer.physical_print);
var printer_id = parseInt(response.printer.id);
var data = response.transactions;
console.log(response);
$.each(data, function (i, dataitem) {
console.log(dataitem);
idList.push(dataitem.id);
});
var latestID = Math.max.apply(Math, idList);
function getData() {
$.ajax({
type: 'POST',
url: '{{ ... }}',
dataType: 'json',
data: {latestID: latestID, printer_timer: printer_timer, printer_storeid: printer_storeid, printer_category: printer_category},
success: function (data) {
console.log(data);
data = data.transactions;
if (data != 0) {
var idList = [];
$.each(data, function (i, dataitem) {
console.log(dataitem);
idList.push(dataitem.id);
});
var latestID = Math.max.apply(Math, idList);
console.log(latestID);
}
}
});
}
getData();
setInterval(function () {
getData();
}, 10000);
}
});
If I console.log(latestID) inside the success: function it shows the correct value, but ajax posts data: {latestID: latestID}, value 1 on each setInterval run.
*EDIT: added entire code.
instead of var latestID = Math.max.apply(Math, idList);
use latestID = Math.max.apply(Math, idList); in success callback.
using var before the variable declares a method level variable overriding the value of global variable. As you want to keep on using the latestID, you need to have global variable.

Data is lost after ajax call

I've got one ajax call after two previous. I need to pass results of those calls to the new one, so I do the following
$.when(getRespData(), getAxisComponents()).done(function (respData, axisData) {
var a = respData; //everything is ok
var b = axisData; //everything is ok
$.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName+ '&type=' + 'VAL',
success: (function (data) {
var c = respData; //everything is ok
var d = axisData; // Uncaught ReferenceError: axisData is not defined
}
but I've got Uncaught ReferenceError when I try to get my axisData inside my new ajax call, although operations with respData are ok.
My first 2 ajax calls look like
function getRespData() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName + '&type=' + 'RESP',
success: (function (data) {
return data;
})
});
}
function getAxisComponents() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload/axis?runName=' + runName,
success: (function (data) {
return data;
})
});
}
where runName, type, taskName are some params of function which contains all these ajax calls.
How can I fix this error, so that I would be able to access both respData and axisData ind my inner ajax call?
i solved it putting async false and declaring an array out of ajax call, like this
let array = [];
$.ajax({
url: path,
type: 'GET',
async: false,
dataType: 'json',
success: function(response){
array = response;
}
});
return array;
You're calling data in your success function but data isn't set before this.
In a jQuery .ajax function, data is the data that is sent to the server when performing the Ajax request, which is why you may think it is lost (because it was never there).
Consider the following:
$.ajax({
data: {"data": data},
dataType: "json",
url: 'yourURl',
success: function(data){
return data;
}

Accessing JSONP data outside of ajax call in jQuery

Now that every google link in the first 5 pages of results is :visited in my browser, I needed to ask...
How can I get the JSON data working so that I can access it/manipulate it in other methods?
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
// works here
console.log(data);
// works here as well & fires local function
testing(data);
// doesnt store
var testvar_1 = data;
}
});
// undefined
console.log(testvar_1);
function testing(data) {
// logs when called from above
console.log(data);
// doesnt store
var testvar_2 = data;
}
// undefined
console.log(testvar_2);
// havent found this yet...
return magicVariableThatLetsMeAccessJSON
}, ...
any ideas? i know theres a lot of other similar questions on stack overflow, but i have found nothing that solves this.
thanks
UPDATE
var storage;
var yourobj = {
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
storage = data;
// logs correctly
console.log(storage);
}
});
}
}
//undefined
console.log(storage);
yourobj._requestText();
//undefined
console.log(storage);
Firstly as noted elsewhere, you need a variable that's in scope, secondly you need to make sure it's not evaluated before the callback is called.
The only way to ensure that is to make the call to _otherMethod inside the success call back method
_otherMethod: function(text) {
//...do what ever you need to do with text
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
_otherMethod(data);
},
}
});
}
callbacks are asyncronous meaning they are called at some point in time that's not determined by the sequence of code lines.
If you know the code using the returned data is never going to be call before the success call back has executed and you need to hold on to the data you can change the code to
_otherMethod: null, //not strictly needed
_requestText: function() {
self = this;
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
self._otherMethod = function(data){
return function(){
//do what you need to with data. Data will be stored
//every execution of _otherMethod will use the same data
console.log(data);
}
}
},
}
});
}
Very simple. You need a storage variable outside of the context of the callback function.
var storage;
var yourobj = {
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
storage = data;
}
});
}
}
Alternatively, storage can be a property on the same object.
By adding var before your variable name, you create a local variable in the current scope.
This doesn't work:
var a = 2;
(function() {
var a = 3;
})();
console.log(a); // 2
While this does:
var a = 2;
(function() {
a = 3;
})();
console.log(a); // 3
Since the variable that you're trying to set is in an outer scope, get rid of var when working with it in an inner scope.
might be this way:
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
var testvar_1;
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
console.log(data);
testing(data);
testvar_1 = data;
}
});
// should work here
console.log(testvar_1);
Actually you were creating a new instance of that var there.

Categories

Resources