I'm chaining getJSON requests with .when.
Code is similar to this:
$.when( $.getJSON(url0),$.getJSON(url1), $.getJSON(url2)).done( function() {
$.each(arguments, function(index, result) { …
How can I write this so if the URL set contains url3 or url4 or more or only url0 it can proceed?
I store the url vars in a file or in local storage.
var list = ['obj1', 'obj2', 'obj3', 'obj4', 'obj5'];
var callback = function() {
console.log("done");
};
var requests = [];
for(i = 0; i < list.length; i++) {
requests.push($.ajax({
url: 'url',
success: function() {
console.log('suc');
}
}));
}
$.when.apply(undefined, requests).then(function(results){callback()});
You can give me some more details so i can load that in array and can show you how that works
JSFIDDLE DEMO : http://jsfiddle.net/MBZEu/4/
or you can try
var urlArr = ['url1', 'url2', 'url3', 'url4', 'url5'];
var callback = function() {
console.log("done");
};
var requests = [];
for(i = 0; i < urlArr.length; i++) {
requests.push($.getJSON(urlArr[i])); //or something similar which can push url in array
}
$.when.apply(undefined, requests).then(function(results){callback()});
or use this to see whats going on with req
requests.push($.getJSON(urlArr[i], function(res){console.log(res)}));
Related
var message = $("#send_message").val();
var Teaminput = $("#sms_reminder_team").val();
for (var i = 0; i <Teaminput.length; i++)
{
var team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
var members=Memberinput[i];
}
Get 2 varaibles as array members and team
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
How to send both array variables using AJAX from current page to "dir_sendmessage".
Change the below line
var parameter = "message="+message+"&team="+team+"&members="+members;
to
var parameter = "message="+message+"&team="+JSON.stringify(team)+"&members="+JSON.stringify(members);
Edit: Modify like this too
var team = [];
var members = [];
for (var i = 0; i <Teaminput.length; i++)
{
team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
members=Memberinput[i];
}
Note: When you add var in each line in the loop, it will declare a new variable. You have to edit like the above code
After update the code with the JSON.stringify() function, you will be able to get the value as an array in you PHP code
Ajax will not directly pass Jquery array to PHP
First of all ideally you should send in JSON format or use array.tostring() ( can avoid this )
But if you have to send it as array you can try following:
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: {team:team, members: members},
success: function(data) {
document.getElementById('check').innerHTML = data; } });
var message = $("#send_message").val();
var teaminputt = $("#sms_reminder_team").val();
team = new Array();
members = new Array();
for (var i = 0; i <teaminputt.length; i++)
{
var team=teaminputt[i];
}
var memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <memberinput.length; i++)
{
var members=memberinput[i];
}
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
$("#msg-send-btn").click(function() {
var message = $("#send_message").val();
var optionsmembers = $('#sms_reminder_members option:selected');
var members = $.map(optionsmembers ,function(option) {
return option.value;
});
//---- Using $.map get all selcted data as a an Array.
var postData = {
message,
members
}
//---- For Avoid Json-Stringfy.
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage.php',
type: 'POST',
data:{myData:postData},
//----- And It's Work Perfectly.
After asking a question and getting a very helpful answer on what the 'Async Juggling' assignment in learnyounode was asking me to do, I set out to implement it myself.
The problem is, my setup isn't having any success! Even though I've referred to other solutions out there, my setup simply isn't returning any results when I do a learnyounode verify myscript.js.
GIST: jugglingAsync.js
var http = require('http');
var app = (function () {
// Private variables...
var responsesRemaining,
urls = [],
responses = [];
var displayResponses = function() {
for(var iterator in responses) {
console.log(responses[iterator]);
}
};
// Public scope...
var pub = {};
pub.main = function (args) {
responsesRemaining = args.length - 2;
// For every argument, push a URL and prep a response.
for(var i = 2; i < args.length; i++) {
urls.push(args[i]);
responses.push('');
}
// For every URL, set off an async request.
for(var iterator in urls) {
var i = iterator;
var url = urls[i];
http.get(url, function(response) {
response.setEncoding('utf8');
response.on('data', function(data) {
if(response.headers.host == url)
responses[i] += data;
});
response.on('end', function() {
if(--responsesRemaining == 0)
displayResponses();
});
});
}
};
return pub;
})();
app.main(process.argv);
Question: What am I doing wrong?
This line
for(var iterator in urls) {
doesn't do what you think it does. It actually loops over the properties of urls (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in). Instead, you have to do something like
for(var i = 0; i < urls.length; i++) {
var url = urls[i];
...
}
or
urls.forEach(function(url, index) {
...
});
In addition to not properly looping through the arrays inside the app module, I was also not properly concatenating data returned from the response.on('data') event. Originally I was doing...
responses[index] += data;
Instead, the correct thing to do was:
responses[index] = responses[index] + data;
Changing that, as well as the things noted by #arghbleargh got the 'Async Juggling' to fully verify!
I have tested my code and it all worked:
~ $ node juggling_async.js site1 site2 site3 site4 ...
The JS code does not limit only to three sites.
var http = require('http');
// Process all the site-names from the arguments and store them in sites[].
// This way does not limit the count to only 3 sites.
var sites = [];
(function loadSites() {
for(var i = 2, len = process.argv.length; i < len; ++i) {
var site = process.argv[i];
if(site.substr(0, 6) != 'http://') site = 'http://' + site;
sites.push(site);
}
})();
var home_pages = [];
var count = 0;
function httpGet(index) {
var home_page = '';
var site = sites[index];
http.get(site, function(res) {
res.setEncoding('utf8');
res.on('data', function(data) {
home_page += data;
});
res.on('end', function() {
++count;
home_pages[index] = home_page;
if(count == sites.length) {
// Yahoo! We have reached the last one.
for(var i = 0; i < sites.length; ++i) {
console.log('\n############ Site #' + (+i+1) + ': ' + sites[i]);
console.log(home_pages[i]);
console.log('============================================\n');
}
}
});
})
.on('error', function(e) {
console.log('Error at loop index ' + inddex + ': ' + e.message);
})
;
}
for(var i = 0; i < sites.length; ++i) {
httpGet(i);
}
Following is the code, which is consoling the response but unable to set the response to store in $scope.dateWiseData array. Let me know what I am doing wrong.
$scope.dateWiseData = [];
var tmpArr = [];
var x = 0;
for (var i=0; i< 7;i++) {
$http.post('/api/getdata', {_id: currentUser._id, data: data}).then(function(response){
console.log(response.data);
tmpArr.push(response);
if ( x < 7 ) {
$scope.dateWiseData = tmpArr;
}
x++;
});
}
console.log("--Week Data Array--");
console.log($scope.dateWiseData);
if you try to print the console.log($scope.dateWiseData); this will execute before the $scope.dateWiseData array is assigned to data which means this will print before the data is getting from server. but your data should be assigned to that array after the http is completes. You need to check the promises in javascript
$scope.getData() = function(){
var deferred = $q.defer();
for (var i=0; i< 7;i++) {
$http.post('/api/dayavailability', {_id: SessionService.currentUser._id, weekDay: new Date($scope.sevenWeekDayArr[i]).toISOString()}).then(function(response){
tmpArr = response.data;
if ( x < 7 ) {
$scope.dateWiseData.push(tmpArr);
}
if(x==6) {
deferred.resolve();
}
x++;
});
}
return deferred.promise;
}
wrapt that for loop like this
and
$scope.getData().then(function() {
// processing
});
** Dont forget to add $q in as a parameter in the controller **
I am trying to make a google shortener analytic tools by javascript, it's my code:
<script>
function makeRequest() {
for (var i=0; i < shortUrl.length; i++){
var url = shortUrl[i];
var request = gapi.client.urlshortener.url.get({
'shortUrl': url,
'projection':'FULL',
});
request.execute(function(response) {
console.log(response); //here is the problem begin
var result = {
short: response.id,
clicks: response.analytics.allTime.shortUrlClicks
};
appendResults(result, i);
});
}
}
function load() {
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
gapi.client.load('urlshortener', 'v1', makeRequest);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
the result would me different everytime!
ex:
shortUrl[1,2,3,4]
it will return 3,2,1,4 or 1,2,4,3......etc
what's wrong is my code?
is the async problem? how could i fix it?
please help me!
thx
Because ajax is asynchronous. You have to use promises.
jQuery example.
var promises = [];
for (var i=0; i < shortUrl.length; i++){
var dfd = new $.Deferred;
var url = shortUrl[i];
var request = gapi.client.urlshortener.url.get({
'shortUrl': url,
'projection':'FULL',
});
request.execute((function(dfd){return function(response) {
dfd.resolve(response);
};})(dfd));
promises.push(dfd.promise());
}
$.when.apply($, promises).done(function(){
promises = undefined;
for(var i in arguments){
var response = arguments[i];
console.log(response); //here is the problem begin
var result = {
short: response.id,
clicks: response.analytics.allTime.shortUrlClicks
};
appendResults(result, i);
}
});
My working code:
var promises = [];
var request = function(i, callback){
setTimeout(function(){return callback(i);},100 - i);
}
for (var i=0; i < 10; i++){
var dfd = new $.Deferred;
request(i, (function(dfd){return function(response) {
dfd.resolve(response);
};})(dfd));
promises.push(dfd.promise());
}
$.when.apply($, promises).done(function(){
promises = undefined;
for(var i in arguments){
console.log(arguments[i]);
}
});
I have a following javascript program:
function jQueryFunction(url, callback)
{
$.ajax
({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
return callback(json);
}
});
}
var jsonArray = new Array();
for(var i = 0; i < 10; i++)
{
jQueryFunction(url[i], function(json){
jsonArray[i] = json;
});
}
//process jsonArray
However, when I check jsonArray after the for loop, it is null. So my question is that how to store the return value from jQueryFunction to jsonArray in for loop and then process it?
I have tried $.when.apply($,jsonArray).done(function) but still the same, it is null.
A simple way:
function doTheAjax(url, callback) {
return $.ajax({
type: "GET",
async: true,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler"
});
};
var reqs = [];
for(var i = 0; i < 10; i++) {
reqs.push(doTheAjax(url[i]));
}
// send the array of requests to when, which will fire `done`
// when it's, well, done
$.when.apply($.when, reqs).done(function() {
$.each(arguments, function(data) {
// process the data
});
});
alternatively, make a bunch of requests and put them into jsonArray, but keep
track of how many you're making. When they all complete, you have the array. Create your
own deferred, resolve it yourself when the counter is up, and return the promise.
var getJSON = function(url) {
var dfd = $.Deferred();
var count = 0;
var total = 10;
var jsonArray = [];
for(var i = 0; i < total; i++) {
doTheAjax(url[i]).done(function(json) {
jsonArray.push(json);
count++;
if ( count >= total ) {
dfd.resolve(jsonArray);
}
});
}
return dfd.promise();
};
getJSON().done(function(theCreatedJsonArray) {
// do stuff
});
I'm not sure why the answer to your previous question (using deferreds) didn't work. But the cause of your problem is that you are checking the array before any of the ajax responses arrived. You also have a problem with i referencing the same value on all callbacks.
One simple workaround, if you know how many responses you're expecting:
var arr = [];
for(var i = 0; i < 10; i++){
jQueryFunction(url[i], function(json){
arr.push(json);
if(arr.length == 10) {
// All 10 responses arrived!
// DO STUFF FROM HERE
// e.g., call another function
console.log(arr);
}
});
}