facebook - Saving FB.api call's response to an array with a for loop with Javascript -
i'm trying code script 1) reads fb user ids text input fields & loops them array 2) calls fb.api each of ids first name , saves returned first name value array. problem: reason, first names received fb.api save same array index place 5. weird since loop should go indexes 1 4.
<script type="text/javascript"> var ids = new array(); var names = new array(); var fields = 4; function firstnames() { var i; var k; (i=1;i<=fields;i++) { ids[i] = document.getelementbyid("field"+i).value; } (k=1; k<=fields; k++) { fb.api('/'+ids[k], function(response) { names[k] = response.first_name; alert(k+' test '+names[k]); }); } } </script>
has ran similar? appreciated.
thanks beforehand.
read: javascript, node.js , loops
see: experiment #7: closure new scope establishing new variable
url: http://blog.mixu.net/2011/02/03/javascript-node-js-and-for-loops
i had same issue i.e. fb.api gets loops final iteration index...
please try solution:
for (k=1; k<=fields; k++) { // closure new scope establishing new variable (function() { var index = k; // new variable fb.api('/'+ids[index], function(response) { names[index] = response.first_name; alert(index+' test '+names[index]); }); }(); }
update: 1 thing note alerts in example won't happen in sequence i.e. might 1,4,2,3... depends on network latency of each api call order executed in ...
Comments
Post a Comment