JSON return value to global variable - javascript

Simply my code looks like this:
var thevariable = 0;
For(){
//somecode using thevariable
$.getJSON('',{},function(e){
//success and i want to set the returned value from php to my variable to use it in the forloop
thevariable = e.result;
});
}
my main problem that the variable value stays "0", during the whole For loop, while i only want it to be "0" at the first loop, then it takes the result returned from PHP to use it on for loop.
here it my real code if you need to take a look:
var orderinvoice = 0;
for(var i=0; i<table.rows.length; i++){
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g,'')).replace(/Qty /g,'');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g,'');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', {'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink}, function(e) {
console.log();
document.getElementById("result").innerText= document.getElementById("result").innerText + "Order #"+e.result+" Created Successfully ";
document.getElementById("invoker").innerText = ""+e.invoice;
orderinvoice = e.invoice;
if(i+1 == table.rows.length){
document.getElementById("result").innerText= document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
});

in a loop block, before one ajax complete other one will be run and this's javascript natural treatment. For your case you can call a function at the end of success event. Do something like this:
var i = 0;
doSt();
function doSt() {
var orderinvoice = 0;
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g, '')).replace(/Qty /g, '');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g, '');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', { 'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink }, function(e) {
console.log();
document.getElementById("result").innerText = document.getElementById("result").innerText + "Order #" + e.result + " Created Successfully ";
document.getElementById("invoker").innerText = "" + e.invoice;
orderinvoice = e.invoice;
if (i + 1 == table.rows.length) {
document.getElementById("result").innerText = document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
i++;
if (i < table.rows.length) doSt();
});
}

I think you need a recursive function that always deals with the first element in your rows array and then splices it off and calls itself. For example, something like this:
function getStuff(rows, results) {
if (rows.length > 0) {
var ordername = rows[0].cells[5].innerText;
$.getJSON('orderprocess.php', { 'ord_name': ordername }, function (e) {
// do some stuff
results.push('aggregate some things here?');
rows.splice(0, 1);
return getStuff(rows, results);
});
} else {
return results;
}
}
When the array is spent, results will be returned with whatever aggregate you wanted at the end of the cycle. Then, you can do as you please with the results. I think you can also manipulate the DOM inside the function as you see fit if that makes more sense. Hope this helps.

Related

how to return this value from my function? is it wrong method?

I don't understand how to solve the following problem when return the value from nested function. is it wrong method. How can I get it?
My basic purpose is to get array values (all coordinates) from var mymap_coordinates, but it can't. that's why I use .toString() to test.
*<script>
mymap.on( //leftlet code
'contextmenu',
function (event)
{
var tg_marker = L.marker(event.latlng, {icon: treegroupIcon}).addTo(mymap);
store_coordinates[incre_coord] = new Point(tg_marker.getLatLng().lat.toFixed(8), tg_marker.getLatLng().lng.toFixed(8));
var n = store_coordinates.length;
var mymap_coordinates = abcdefg(store_coordinates, n);
window.alert (mymap_coordinates.toString()); //This alert can't print all array value when return the value from abcdefg function
incre_coord = incre_coord + 1;
}
);
function abcdefg(points, n)
{
.......
.......
.......
// return Result
var num = 0;
var map_coordinate = new Array();
for (let temp of abc.values())
{
map_coordinate[num] = "[" + temp.x + ", " + temp.y + "]";
num = num + 1;
}
window.alert (map_coordinate.toString()); //This alert can print all array value
return map_coordinate;
}
</script>*

loop through selected checkboxes

In the checkboxes which pertains on the same class ,I'm using this function (not finished) tho loop and set a string
function estados() {
var query = "trucades.estat in(";
var checks = $('.estate_check:checked');
if (checks.length === 0) {
query = "not selected ";
} else {
//set the message here ...but only loops once
}
return query;
}
But checks only contains an object which contains the selected checkboxes but if I try to llop ,it only loops once ,because only contains this object
var ckbox = $('.my-checkbox:checked');
var str = "";
ckbox.each(function(){
str += $(this).attr('data-text') + ", ";
});
alert(str);
This fiddle helps you figure it out:
JSFiddle
Assuming you need to create query, You can use .map() along with .get() to create an array of selected values. then Array.join() can be used to create comma separated string.
function estados() {
var query = "trucades.estat in(";
var checks = $('.estate_check:checked');
if (checks.length === 0) {
query = "not selected ";
} else {
//Create an array of selected value
var selectedValue = checks.map(function () {
return $(this).val();
}).get();
query += selectedValue.join(',') + ')'
}
return query;
}
function estados() {
var query = "trucades.estat in(";
$('.estate_check:checked').each(function( index ) {
const val = $( this ).val()
console.log(index + ': ' + val);
query += val;
});
query += ')';
return query;
}

Javascript Callback in for Loop

My problem is that I'm having a Function A which calls at one point another function, let's call it Function B (getChildContent) and needs the return value of Function B in order to proceed. I know that it's because of Javascripts Asynchronous Nature, and i tried to solve it with a callback. But i can't get it work properly.
FunctionA(){
//some Code.....
else {
for(i in clustertitles) {
if(S(text).contains(clustertitles[i])) {
var parent = {};
parent.ClusterName = clustertitles[i];
parent.Functions = [];
var str = '== ' + clustertitles[i] + ' ==\n* ';
str = S(text).between(str,'.').s;
var caps = parseFunctions(str);
for(y in caps) {
//var content = getChildContent(caps[y]);
getChildContent(caps[y], function(content) { //Function call
var child = {};
child.FunctionName = caps[y];
child.Content = [];
child.Content.push(content);
parent.Functions.push(child);
console.log(content);
});
}}}
}
function getChildContent (capname, callback) {
t = capname.replace(' ', '_');
bot.page(t).complete(function (title, text, date) {
var str = S(text).between('== Kurzbeschreibung ==\n* ', '.').s;
if(str === undefined || str === null || str === '') {
throw new Error('Undefined, Null or Empty!');
}
else {
var content = {};
str = parseTitles(str);
content.Owner = str[0];
content.Aim = str[1];
content.What = str[2];
content.Who = str[3];
content.Steps = str[4];
content.Page = 'some URL';
callback(content);
}
});
}
So in Function A I'm trying to call getChildContent from a for-Loop and pass the current string from caps-array. For each String in caps-array getChildContent() makes a http request over a node.js module and retrieves a string. With this string i'm building an object (content) which is needed in Function A to continue. However the 'console.log(content)' in Function A just prints out the object which is created with the last string in caps-array, but for many times. E.G. if caps-array has 5 entries, i get 5 times the object which is created with the last entry of caps-array.
How can i manage the loop/callback to get every time the right object on my console?
Your loop should call another function that preserves the value of y, something like this:
FunctionA(){
//some Code.....
else {
for(i in clustertitles) {
if(S(text).contains(clustertitles[i])) {
var parent = {};
parent.ClusterName = clustertitles[i];
parent.Functions = [];
var str = '== ' + clustertitles[i] + ' ==\n* ';
str = S(text).between(str,'.').s;
var caps = parseFunctions(str);
for(y in caps) {
yourNewFunction (y, caps, parent);
}}}
}
function yourNewFunction (y, caps, parent) {
getChildContent(caps[y], function(content) { //Function call
var child = {};
child.FunctionName = caps[y];
child.Content = [];
child.Content.push(content);
parent.Functions.push(child);
console.log(content);
});
}
function getChildContent (capname, callback) {
t = capname.replace(' ', '_');
bot.page(t).complete(function (title, text, date) {
var str = S(text).between('== Kurzbeschreibung ==\n* ', '.').s;
if(str === undefined || str === null || str === '') {
throw new Error('Undefined, Null or Empty!');
}
else {
var content = {};
str = parseTitles(str);
content.Owner = str[0];
content.Aim = str[1];
content.What = str[2];
content.Who = str[3];
content.Steps = str[4];
content.Page = 'some URL';
callback(content);
}
});
}
There are 2 ways to do so.
Put the loop inside a function, execute your callback after the loop is done. (Problematic if you are doing async call inside the loop.
function doLoopdiloopStuff() {
for() {
}
callback();
}
The other way, the way i prefer looks like this:
for(var i = 0; i < stuff || function(){ /* here's the callback */ }(), false; i++) {
/* do your loop-di-loop */
}
In another example:
for (var index = 0; index < caps.length || function(){ callbackFunction(); /* This is the callback you are calling */ return false;}(); index++) {
var element = caps[index];
// here comes the code of what you want to do with a single element
}

Array length remains 0 even though I push 'objects' to it

I have a little piece of code that reads some ajax (this bit works) from a server.
var self = this;
var serverItems = new Array();
var playersOnlineElement = $("#playersOnline");
function DataPair(k, v) {
this.key = k;
console.log("new datapair: " + k + ", " + v);
this.value = v;
}
DataPair.prototype.getKey = function() {
return this.key;
}
DataPair.prototype.getValue = function() {
return this.value;
}
$.getJSON("http://127.0.0.1", function(data) {
$.each(data, function(key, val) {
var pair = new DataPair(key, val);
self.serverItems.push(pair);
});
});
console.log(serverItems.length); //Problem is here
for (var i = 0; i < serverItems.length; i = i + 1) {
var dpair = serverItems[i];
if (dpair.getKey() === "playersOnline") {
self.playersOnlineElement.text("Players Online: " + dpair.getValue());
}
}
The datapair and the JSON get loaded but when they are pushed to the array it doesn't seem to work. I tried with self.serverItems and just serverItems because netbeans showed me the scope of the variables being good if I used just serverItems but I am a bit confused as to why this doesn't work. Can anyone help me?
I put in comments where the error is. serverItems.length is 0 even though when debugging in a browser in the DOM tree it has an array serverItems with all the data inside.
Assumingly this serverItems is in another scope and not the one I am calling when I want to get the length?
add this code into the success part, since its asynchronous...
for (var i = 0; i < serverItems.length; i = i + 1) {
var dpair = serverItems[i];
if (dpair.getKey() === "playersOnline") {
self.playersOnlineElement.text("Players Online: " + dpair.getValue());
}
to...
$.getJSON("http://127.0.0.1", function(data) {
$.each(data, function(key, val) {
var pair = new DataPair(key, val);
self.serverItems.push(pair);
for (var i = 0; i < serverItems.length; i = i + 1) {
var dpair = serverItems[i];
if (dpair.getKey() === "playersOnline") {
self.playersOnlineElement.text("Players Online: " + dpair.getValue());
}
});
});

JS and jQuery, global object gets empty when function is finished

I have a problem with an object dict. When json datas are received, program calls LoadDict() function, where dict object gets filled with new data from server. I used FireBug to make sure that dict has all new elements with correct information, but when function is finished, dict gets empty again like it was before ajax request. This code executes in the global scope:
var dict = new Dictionary();
function LoadDict(words) {
for (var i in words) {
var word = new Word();
word.word = words[i].Word;
word.transcript = words[i].Transcript;
word.frequency = words[i].Frequency;
word.meanings = words[i].Meanings;
word.examples = words[i].Examples;
word.imgLinks = words[i].ImgLinks;
dict.Add(word);
}
}
$.getJSON("getall").done(LoadDict);
dict.PrintDictionary);
And this is some code of my Dictionary class
function Dictionary() {
this.collection = new Array();
this.count = 0;
this.sorted = false;
}
Dictionary.prototype.Add = function(word) {
if (word instanceof Word) {
word.id = this.count;
this.collection[this.count] = word;
this.count++;
this.sorted = false;
}
}
Dictionary.prototype.PrintDictionary = function() {
function WordToString(word) {
var line = "<strong>" + word.word + "</strong> [" + word.transcript + "] - " + word.meanings[0];
for (var j = 1; j < word.meanings.length; j++) {
line += ", " + word.meanings[j];
}
return line;
}
var result = "<ol>"
for (var i = 0; i < this.collection.length; i++)
result += "<li>" + WordToString(this.collection[i]) + "</li>";
result += "</ol>"
document.write(result);
}
Declaration of Dictionary class goes before creating dict object.
Help, please!
A timing problem.
In your code, PrintDictionary function have excuted before ajax call is complete.
The problem is that the $.getJSON is async.
This means that the dict.PrintDictionary(); line gets executed before the result is returned from the getJSON call

Categories

Resources