This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Asynchronous Process inside a javascript for loop [duplicate]
(6 answers)
Closed 5 years ago.
I'm trying to create a JavaScript object (friends_ringsigs), in which the keys are the values of names[i], and the values are the "result" variable created at the execution of the promise. The problem is, when I try to access the "names[i]" variable for use, it doesn't exist.
// get list of new contact requests
$.ajax({
url: '/api/messaging/getnewfriends.php?auth=<?=$_SESSION['auth_random']?>',
type: 'POST',
data: '',
success: function(result) {
if(result != 'none'){
var names = result.split("[Delimiator0]");
for(var i = 0; i < names.length-1; i++){
ringsig_decrypt(priv_ck, names[i]).then(function(result){
friends_ringsigs[result] = names[i];
alert(friends_ringsigs[result]);
alert(names[i]);
alert(result);
document.getElementById('newcontactslist').innerHTML += contactify(result);
$('#contactslabel').show();
});
}
}else{
document.getElementById('newcontactslist').innerHTML = "";
$('#contactslabel').hide();
}
}
});
I'm able to access the "result", but not the names[i], and later when I go to get the value out of friends_ringsigs, it doesn't exist. In fact, alert(JSON.stringify(friends_ringsigs)); outputs "{}".
Related
This question already has answers here:
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 5 years ago.
Javascript: I have a dynamically filled array named resultsAuthor, when I log this object, I get this. (logged it because I need the length to loop through the object and this wasn't working) 1
But when I try to log resultsAuthor.length, I get 0.
Anyone know what I'm doing wrong?
This is in my utils.js
From there I call it in my main.js like this:
var searchCriteria = document.querySelector('[title="tbxZoeken"]').value;
var searchAuthor = new Utils.GetBookinfoByAuthor(searchCriteria);
var resultsAuthor = searchAuthor.loadData();
console.log(resultsAuthor); // returns the object
console.log(resultsAuthor.length); // returns 0
Thanks!
Your ajax call has probably not finished loading when you print resultsAuthor.length, so it return 0.
If you print resultAuthor this is still a reference to the original variable, so it gets printed correctly.
To fix this you can use a callback function or a promise. With a callback you could do something like this:
In your utils.js
GetBookinfoByAuthor: function (auteur) {
//...
this.loadData = function(callback) {
// Rest of your code...
// Request returned sucessfully
if (xhr.status === 200) {
//Rest of your code....
for (var i = 0; i < data.length; i++) {
// add all books to array
}
// All books a loaded
callback(books)
}
}
}
In your main.js
var searchCriteria = document.querySelector('[title="tbxZoeken"]').value;
var searchAuthor = new Utils.GetBookinfoByAuthor(searchCriteria);
searchAuthor.loadData(function() {
console.log(resultsAuthor);
console.log(resultsAuthor.length);
});
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I have one problem with javascript global variable,namely,i have global variable niz_opcija2,and i initialize it in one function,but in other function,it says it is undefined..
this is my javascript:
var niz_opcija2=[];
window.onload=function(){
ucitaj2();
ucitajKategorije();
}
function ucitaj2(){
$.get("/manager/categoriesArticle",function(data){
niz_opcija2.push(data);
console.log(data);
var select=document.getElementById("select3");
for(var i=0;i<niz_opcija2[0].length;i++){
var option=document.createElement("option");
option.value=niz_opcija2[0][i].categoryCode;
option.innerHTML=niz_opcija2[0][i].name;
option.id=niz_opcija2[0][i].name;
select.appendChild(option);
}
});
}
function ucitajKategorije(){
for(var i=0;i<niz_opcija2[0].length;i++){
var select=document.getElementById("selectKateg");
var option=document.createElement("option");
option.value=niz_opcija2[0][i].name;
option.innerHTML=niz_opcija2[0][i].name;
option.id=select.length;
select.appendChild(option);
}
}
(in this code i am trying to get data as json using $.get,and add it to select lists select3 and selectKateg,and ucitaj2() function is getting the data,but ucitajKategorije isn't,but I think it should work the same?)Does anyone know what can be the problem?Thanks in advance!
The issue is happening because your intialization of niz_opcija2 happens inside an asynchronous function call.
ucitaj2 returns immediately before $.get("/manager/categoriesArticle" has returned with data form the server.
Change to calling it in the get succes function:
var niz_opcija2=[];
window.onload=function(){
ucitaj2();
}
function ucitaj2(){
$.get("/manager/categoriesArticle",function(data){
niz_opcija2.push(data);
console.log(data);
var select=document.getElementById("select3");
for(var i=0;i<niz_opcija2[0].length;i++){
var option=document.createElement("option");
option.value=niz_opcija2[0][i].categoryCode;
option.innerHTML=niz_opcija2[0][i].name;
option.id=niz_opcija2[0][i].name;
select.appendChild(option);
}
//Call it here
ucitajKategorije();
});
}
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I'm new to this so i guess i'm missing something simple. The foor loop works fine but inside it i get an undefined variable
var categories_info = ["historia","excelencia","arte","social","instalaciones","padres","familia"];
for ( var i = 0; i < categories_info.length; i++) {
$("#showMe-"+categories_info[i]).click(function(){
$(".info."+categories_info.[i]).addClass("info-show");
console.log(".info."+categories_info[i]); //debug is undefinded
});
};
You need to create a closure like
var categories_info = ["historia", "excelencia", "arte", "social", "instalaciones", "padres", "familia"];
for (var i = 0; i < categories_info.length; i++) {
(function(i) {
$("#showMe-" + categories_info[i]).click(function() {
$(".info." + categories_info[i]).addClass("info-show");
console.log(".info." + categories_info[i]);
});
})(i);
};
This method is known as an IIFE
Basically, what was happening is the variable i was unavailable to the callback when the actual click happened.
However, by passing i in a self-executing anonymous function, you have created a closure which will preserve i and is accessible to the click handler.
Use a closure. Change:
$("#showMe-"+categories_info[i]).click(function(){
$(".info."+categories_info.[i]).addClass("info-show");
console.log(".info."+categories_info[i]); //debug is undefinded
});
To:
(function( i ) {
$("#showMe-"+categories_info[i]).click(function(){
$(".info."+categories_info.[i]).addClass("info-show");
console.log(".info."+categories_info[i]);
});
})( i );
This question already has answers here:
passing index from for loop to ajax callback function (JavaScript)
(3 answers)
Closed 8 years ago.
I'm sure this has been asked before, but I don't know what to search for.
So I want function to be called with a string that corresponds with the item clicked, but I want to simply add any new items to an array of strings.
var menuList = ["overview", "help", "search"];
var functionCalls = [
function() { toggleMenu(menuList[0]); },
function() { toggleMenu(menuList[1]); },
function() { toggleMenu(menuList[2]); },
];
which is used like this in a loop: $("something").click(functionCalls[i])
This is what I want to do (but obviously it doesn't work):
for (var i in menuList) {
// This does not work because the closure references 'i'
// which, at the end, is always the index of the last element
$("something").click(function() {
toggleMenu(menuList[i]);
});
// this works, but I have to define each closure
$("something").click(functionCalls[i]);
}
How can I create an anonymous function that accepts a value based on a variable - but doesn't retain the reference to the variable?
You could use an IIFE like this:
for (var i=0; i<menuList.length; i++) {
!function( index ) {
$("something").click(function() {
toggleMenu( menuList[index] );
});
}( i );
}
By calling the anonymous function, you create a local copy of the current value for i with the name index. Hence, all handlers receive their respective version of i.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript closure inside loops - simple practical example
I am using webservice to get the data in the form of JSON by using javascript and want to store that data in Sqlite Database. here i used for loop to store data one by one in Database by executeSql Query. But problem is function inside the for loop getting "i" value out of scope means showing undefined. I am trying to solve this problem by last 5 days. Any suggestion ?
Thanks
function GetGeoValues() {
$.get("http://example.in/projects/api.php?usn=user&pwd=****&var=something", function (Jdata) {
var geoid = new Array();
var geoname = new Array();
var i;
for (i = 0; i < Jdata.vact_geography.length; i++) {
geoid.push(Jdata.vact_geography[i].geo_id);
geoname.push(Jdata.vact_geography[i].geo_name);
db.transaction(function (transaction) {
alert(geoid[i]); // here i showing undefined
transaction.executeSql('INSERT INTO vact_geography VALUES(' + parseInt(geoid[i]) + ',"' + geoname[i] + '")');
});
}
});
}
I'm not sure, but this can happen, if function(transaction) executed in asynchronous mode. In this case variable i after for loop is finished must be equals to Jdata.vact_geography.length, and, as result geoid[i] equals to undefined. To workarround this try next:
function GetGeoValues() {
$.get("http://example.in/projects/api.php?usn=user&pwd=****&var=something",
function(Jdata) {
var geoid=new Array();
var geoname=new Array();
for(var i=0;i<Jdata.vact_geography.length;i++) {
geoid.push(Jdata.vact_geography[i].geo_id);
geoname.push(Jdata.vact_geography[i].geo_name);
}
db.transaction(function(transaction) {
for(var i=0;i<geoid.length;i++) {
alert(geoid[i]); // here i showing undefined
transaction.executeSql('INSERT INTO vact_geography VALUES('+parseInt(geoid[i])+',"'+geoname[i]+'")');
// All INSERT's executed in one transaction
}
});
}
);
}
Here inner function and outer function concept is considered. So the outer function have the var i. But in inner function i is not defined. Thats y its throwing error as "undefined"