Using arrays in Ajax - javascript

Here is my original code in Javascript
var wt_val = [];
for (i = 0; i<human_wt.length; i++){
var mult;
mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100));
wt_val.push(mult);
}
wt_val is a list or a list of lists.
Now I am sending this to the server.
$.ajax({
type: 'GET',
url: '/add',
data: {hoot: wt_val},
success: function(results){
alert("success");
},
error: function(error) {
}
});
Again, no error here.
But no value is received here.
app.route('/add', methods=['GET'])
def sum():
start = request.form.getlist('hoot[]')
print type(start)
print len(start)
Length is 0

you will need to do something like this
paramtoget= { pval: wt_val};
in your post
$.post('..abc.aspx' + Math.random()
, {
param: paramtoget
}
on server side
var value = Request.Form("param[pval][]")
Hope this helps

Related

sum values from multiple ajax requests

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...
});

Fill array by multiple AJAX requests, then pass array to another function

(My solution below)
I have several HTML elements with class .canvas-background of which information is stored in the database. I want to get the information of each element and process it via JavaScript. But somehow I can't pass the response of the AJAX request to another function. Here is what I've tried:
function initTabs() {
var tabs = loadTabInformation();
console.log(tabs); // (1)
// do something else
}
function loadTabInformation() {
var requests = new Array();
var tabs = new Object();
var counter = 0;
$(".canvas-background").each(function () {
var tabNumber = $(this).data("tab-number");
var request = $.ajax({
type: 'POST',
url: '../db/GetTabInformation.ashx',
data: String(tabNumber),
dataType: 'json',
contentType: 'text/plain; charset-utf-8'
})
.done(function (response) {
tabs[counter++] = response;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error in loadTabInformation()");
console.log(textStatus);
console.log(errorThrown);
});
requests.push(request);
});
$.when.apply($, requests).done(function () {
console.log(tabs); // (2)
return tabs;
});
}
At (1) I get undefined, but at (2) everything seems to be alright.
THE SOLUTION:
Thanks to the answer and the link in the comment #Kim Hoang provided I got this working. The clue seemed to put the done() function in the calling function, that is initTabs() in my case. Another thing I got wrong was to try to do the logic that should be executed after the AJAX requests had finished outside the done callback function. They must be inside (makes sense, if you think about it). And a lot of conosle output helped, to see what function returns what kind of object.
function initTabs() {
var tabInfoRequest = loadTabInfo();
tabInfoRequest[0].done(function() {
var results = (tabInfoRequest[1].length > 1) ? $.map(arguments, function(a) { return a[0]; }) : [arguments[0]];
for (var i = 0; i < results.length; i++) {
// do something with results[i]
}
});
}
function loadTabInfo() {
var tabNumbers = new Array();
$(".canvas-background").each(function () {
tabNumbers.push($(this).data("tab-number"));
});
var requests = $.map(tabNumbers, function (current) {
return $.ajax({
type: 'POST',
url: '../db/GetTabInformation.ashx',
data: String(current),
dataType: 'json',
contentType: 'text/plain; charset-utf-8'
});
});
var resultObject = new Object();
resultObject[0] = $.when.apply($, requests);
resultObject[1] = requests;
return resultObject;
}
Note: I only did the resultObject-thing because I needed the array requests in the initTabs() function.
Thank you very much for helping me!
You do not return anything in loadTabInformation, so of course you will get undefined. You should do it like this:
function loadTabInformation() {
...
return $.when.apply($, requests);
}
function initTabs() {
loadTabInformation().done(function (tabs) {
console.log(tabs); // (1)
// do something else
});
}

Cannot read property of undefined after JSON parse

I have done an ajax request in my code and it works good. After that I want to extract only the necessary info and re-post it to another script. Until now here is my code:
$.ajax({
type: "POST",
url: url,
data: {xhr_id: xhr_id},
success: function (jsondata) {
var product_data = [];
for (var i = 0; i <= 3; i++) {
//alert(jsondata.products[i].product_description.toSource());
product_data[i] = {};
product_data[i]["product" + i] = jsondata.products[i].product_description;
//alert(product_data[i]["product" + i].toSource());
}
},
dataType: "json"
});
The problem is that both the alerts work fine, displaying the information I want. However, I get an error message of "Uncaught TypeError: Cannot read property 'product_description' of undefined" which breaks the script and prevents me from doing anything else. What am I doing wrong, any ideas?
'product_description' of undefined" what it means is that your are trying to access property on undefined variable. That implies "jsondata.products[i]" resulted in undefined value which have occured due to index out of range.How many records are returned in jsondata 3 or 4,check and adjust the condition in for loop
The parameter in the success() function of $.ajax is a string. You have to put it through a parse function to make json. See your code below modified but not tested.
$.ajax({
type: "POST",
url: url,
data: {xhr_id: xhr_id},
success: function (jsondata) {
var oData;
try { oData=jQuery.parseJSON(jsondata) }
catch(err) {
alert("Problem parsing json string : " + jsondata)
return false
}
var product_data = [];
for (var i = 0; i <= 3; i++) {
//alert(oData.products[i].product_description.toSource());
product_data[i] = {};
product_data[i]["product" + i] = oData.products[i].product_description;
//alert(product_data[i]["product" + i].toSource());
}
},
dataType: "json"
});

Ajax Pagination with jQuery

I need to retrieve data from an api that has a limit on the number of results being returned.
Using the total number of results found, I'm able to make additional additional ajax calls until all data is retrieved. However, I need sort all the data alphabetically before displaying it on the page.
How can I access the data within the array after ALL ajax calls have been successfully made?
Here is what I have so far:
var mydata = [];
function loadPosts() {
var api = 'http://someurl.com';
$.ajax({
url: api,
dataType: 'jsonp',
data: {
rows: 1,
},
success: function(data) {
totalNumberOfRecords = data.numFound;
for (var start = 0; start < totalNumberOfRecords; start += rows) {
$.ajax({
url: api,
dataType: 'jsonp',
data: {
'rows': rows,
'start': start,
},
success: function(data) {
$.each(data.namesList, function(index, item) {
mydata.push(item.firstName);
});
},
});
}
},
});
}
console.log(mydata);
This is an instant-noodle solution.
var numOfAjax = 0;
var numOfResolvedAjax = 0;
for (var start = 0; start < totalNumberOfRecords; start += rows) {
numOfAjax++;
$.ajax({
url: api,
dataType: 'jsonp',
data: {
'rows': rows,
'start': start,
},
success: function(data) {
$.each(data.namesList, function(index, item) {
mydata.push(item.firstName);
});
numOfResolvedAjax++;
// Check if all ajax request has been responded to sort the result.
if (numOfResolvedAjax === numOfAjax) {
sortMyData(myData);
}
},
});
}
For a perfect solution, please check in async library with a lot of functions which can help you. E.g: async.parallel may be what you need.
Honestly, if it were me with this API limit issue, I'd use the server to talk to the API ever-so-often to capture all the data into my own system - beit MySQL or Redis or whatever. Then I would use my front-end JS however I wanted without limmits

Parse Promises Multiple httpRequest Cloud Code

I'm writing an iOs app with Parse.com and Cloud Code. Actually I want to retrieve objects which contain one picture and other informations from a website and I want to add them to a class named News. When I run my code, every object is saved (in my class, one row = one retrieved object) but unfortunately the only first one has its picture saved.... Any idea ?
I made a lot of searches about promises (series / parallels) and I think the problem comes from here..
Note : don't worry about myLink, myImgLink : I put this to make my code easy to read !
Parse.Cloud.define("rajouteNews", function(request, response) {
Parse.Cloud.httpRequest({ url: 'myUrl'}).then(function(httpResponse) {
var news = [];
var NewsClass = Parse.Object.extend("news");
for (var i = 0; i < 10 ; ++i) {
var maNews = new NewsClass();
maNews.set("link", myLink[i]); // "Other informations"
maNews.set("imgLink", myImgLink[i]);
maNews.set("title", myTitle[i]);
var promises = [];
promises.push(Parse.Cloud.httpRequest({
url: $('img').attr('src'),
method: 'GET',
}).then(function(httpResponse){
var imgFile = new Parse.File("photo.jpg", {base64:httpResponse.buffer.toString('base64')});
maNews.set("image",imgFile); // The picture
return maNews.save();
}));
news.push(maNews);
}
promises.push(Parse.Object.saveAll(news, {
success: function (list) {
response.success(news.length.toString() + " ont été sauvegardées");
},
error: function (list, err) {
response.error("Error adding news");
}
}));
return Parse.Promise.when(promises);
}).then(function(bla,result){
response.success("Job done");
}, function(error) {
response.error(error);
}
);
});
Your promises array should put out of the for loop scope. Otherwise , your promise array would be assigned to be a new blank array each loop.
Parse.File would be saved automaticly when its parent do save, you don't need to save it in advance.
So I improve your code as following, try it and tell me weather it works.
Parse.Cloud.define("rajouteNews", function(request, response) {
Parse.Cloud.httpRequest({
url: 'myUrl'
}).then(function(httpResponse) {
var promises = [];
var NewsClass = Parse.Object.extend("news");
for (var i = 0; i < 10; ++i) {
var maNews = new NewsClass();
maNews.set("link", myLink[i]); // "Other informations"
maNews.set("imgLink", myImgLink[i]);
maNews.set("title", myTitle[i]);
var maNewsPromise = Parse.Cloud.httpRequest({
url: $('img').attr('src'),
method: 'GET',
}).then(function(httpResponse) {
var imgFile = new Parse.File("photo.jpg", {
base64: httpResponse.buffer.toString('base64')
});
maNews.set("image", imgFile); // The picture
return maNews.save();
});
promises.push(maNewsPromise);
}
return Parse.Promise.when(promises)
}).then(function(bla, result) {
// this function is call when `Parse.Promise.when(promises)` is done,
//I can't figure out why you take two params.
response.success("Job done");
}, function(error) {
response.error(error);
});
});

Categories

Resources