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 1 year ago.
Any idea why the following return an empty array? I cannot understand or debug this error. Initially, storearray1 returns array with values in it. Subsequent usage, storearray1 returns an empty array. If possible can help provide a solution to this problem. I am confused.
function f1(){
var storearray1=[];
for (var skip = 0; skip < 9000; skip = skip + 500) {
$.ajax({
url: "/api/routes?$skip=" + skip,
success: function(results) {
//Set result to a variable for writing
var objs = JSON.stringify(results);
var routetimeobjs = JSON.parse(objs);
storearray1.push(routetimeobjs['value']);
}
});
}
}
function showresult(){
console.log(storearray1);//work (refer to image)
var actualarray=storearray1;
console.log(actualarray); //does not work- return empty array
}
showresult();
Console Log for storearray1:
Try this.
var storearray1=[];
var calls = [];
for (var skip = 0; skip < 9000; skip = skip + 500) {
(function(skp) {
var c = $.ajax({
url: "/api/routes?$skip=" + skp,
success: function(results) {
//Set result to a variable for writing
var objs = JSON.stringify(results);
var routetimeobjs = JSON.parse(objs);
storearray1.push(routetimeobjs['value']);
}
});
calls.push(c);
})(skip);
}
$.when(...calls).then(() => console.log(storearray1));
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 12 months ago.
function addIDS() {
const imdbIDs = [];
imdbIDs.push("id1");
imdbIDs.push("id2");
...
return imdbIDs ;
}
function getThemoviedbIDs(IDs) {
let arr = [];
let urls = [];
for(let i = 0; i < IDs.length; i++) {
urls.push(`...${imdb_ids[i]}...`);
}
$.each(urls, (i, u) => {
$(function() {
$.ajax({
url: u,
dataType: 'json',
success: function(data) {
arr.push(data.tv_results[0].id);
},
statusCode: {
404: function() {
alert('Err');
}
}
});
});
});
return arr;
}
function getDetails(themoviedbID) {
console.log(themoviedbID);
console.log(`...${themoviedbID[0]}`);
}
const imdbIDs = addIDS();
console.log("IMDB IDs: ", imdbIDs);
const themoviedbIDs = getThemoviedbIDs(imdbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);
const themoviedbIDs = getThemoviedbIDs(themoviedbIDs);
console.log("themoviedbIDs: ", themoviedbIDs);
I am using themoviedb database.
populate() I add imdb IDs to the imdbIDs array, then I get themoviedb IDs by getThemoviedbIDs() function.
In the getDetails() function I would like to make ajax request just like in the getThemoviedbIDs() function, but unfortunatelly there is a problem in there. console.log(themoviedbID) output the appropriate array, but console.log(...${themoviedbID[0]}) output .../undefined...
I can get enough information about the series if I am using themoviedb ID.
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 2 years ago.
With the given code -
var videowallwidth;
var videowallheight;
function getPositions() {
$.ajax({
url: 'https://' + ipaddress + ':46272/NetAPICmd?Command=Output',
type: 'get',
data: '[]',
dataType: 'jsonp',
success: function (response1) {
var msg1 = response1.Result;
var testarray1 = msg1.split("\r\n");
for (var i = 1; i <= testarray1.length - 1; i++) {
var res = testarray1[i].split(':');
var newRes = res;
if (newRes[0] == "TotalSize") {
var ressplit = newRes[1].split('x');
videowallwidth = ressplit[0].trim();
videowallheight = ressplit[1].trim();
}
}
}
});
}
console.log(videowallwidth);
I have defined videowallwidth and videowallheight as global variables and set their values inside getPositions() function, When i console log the variables inside the function they seem fine and have the right values. But when i called them outside the function they show "undefined" which means their values didnt update globally... How do i fix this??
The callback function is asynchronous and you will get the correct value once the process is fully completed. To get the correct value, you need to log value inside the callback function.
function getPositions() {
$.ajax({
url: 'https://' + ipaddress + ':46272/NetAPICmd?Command=Output',
type: 'get',
data: '[]',
dataType: 'jsonp',
success: function (response1) {
var msg1 = response1.Result;
var testarray1 = msg1.split("\r\n");
for (var i = 1; i <= testarray1.length - 1; i++) {
var res = testarray1[i].split(':');
var newRes = res;
if (newRes[0] == "TotalSize") {
var ressplit = newRes[1].split('x');
videowallwidth = ressplit[0].trim();
videowallheight = ressplit[1].trim();
console.log(videowallwidth, videowallheight); // <------------------
}
}
}
});
}
You might want to insert global variables inside the window object, like this:
window.videowallwidth = null; //initialize as you please
window.videowallheight = null; //initialize as you please
Like this, you should be sure they're reachable everywhere
Watch out with ajax, those functions are asynchronous, so you should use callbacks/promises etc.. to manage the "flow"
So, I have a page where I can add foods to an order list and currently I am making the "remove from the list" function as well, but I am facing a problem.
When I call setAttribute() on the right removeButton, I also want to remove the item from my array so that it won't send the removed food's name to the database.
My problem is the following: In the call of setAttribute(), something is wrong with my array, because removeName doesn't get it as a parameter.
var lastid = 0;
var foods_added = [];
var locked = true;
function add_food() {
var food_name = document.getElementById('food_name').value;
$.ajax({
url: "ask-info.php",
type: "post",
data: { food_name : JSON.stringify(food_name) },
success: function(res) {
console.log(res);
if (res == "van") {
var entry = document.createElement('h4');
entry.appendChild(document.createTextNode(food_name));
entry.setAttribute('id','item'+lastid);
var removeButton = document.createElement('button');
removeButton.appendChild(document.createTextNode("Töröl"));
removeButton.setAttribute('onClick','removeName("'+'item'+lastid+', foods_added")');
entry.appendChild(removeButton);
lastid+=1;
list.appendChild(entry);
foods_added.push(food_name);
document.getElementById('food_name').value = "";
document.getElementById('press').disabled = true;
} else {
document.getElementById('press').disabled = true;
}
}
})
}
function removeName(itemid, foods_added){
var item = document.getElementById(itemid);
for (var i = 0; i<foods_added.length; i++) {
if (foods_added[i].id == itemid) {
foods_added.splice(foods_added[i].id, 1);
}
}
list.removeChild(item);
}
It looks like your problem is probably in this line:
removeButton.setAttribute('onClick','removeName("'+'item'+lastid+', foods_added")');
I'd recommend trying this instead:
removeButton.addEventListener('click', () => {
removeName(`item${lastid}`, foods_added);
});
Or if you don't have the ability to use es6:
removeButton.addEventListener('click', function() {
removeName('item' + lastid, foods_added);
});
Going into more detail about why your code isn't working, I imagine it's because the string you're passing in as the second parameter to setAttribute is evaled in a context outside of your calling function. foods_added doesn't exist in that context so it is undefined.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
Im trying to make a simple comment system using React. I'm saving the comments in Parse. The problem is, when I retrieve the comments from Parse, I need to update the state of my component, but when I try to do it, I get an error "Uncaught ReferenceError: this.setState is not defined".
Not working code
loadComments() {
let Comment = Parse.Object.extend("Comment");
let query = new Parse.Query(Comment);
query.limit(15).find({
success: function(result) {
let data = [];
for (var i = 0; i < result.length; i++) {
var object = result[i];
data.push(object.toJSON());
}
this.setState({ data: data });
}
});
}
If I change my code it works, but I think that should have a better approach to this.
Working code
loadComments() {
let Comment = Parse.Object.extend("Comment");
let query = new Parse.Query(Comment);
let _this = this;
query.limit(15).find({
success: function(result) {
let data = [];
for (var i = 0; i < result.length; i++) {
var object = result[i];
data.push(object.toJSON());
}
_this.setState({ data: data });
}
});
}
You have two other options:
Function.prototype.bind:
success: function (result) {
// etc
}.bind(this)
An arrow function (requires es6), which uses the this from the surrounding scope:
success: (result) => {
// etc
}
This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have a javaScript function that use library Buckets and it should return the value to html.
I used console.log to see data inside the function and it's not null. But on the html, it said "undefined".
This is my js code :
function transformToStruct(xmlData)
{
var data = xmlData.item;
var myReturn;
$.getScript("buckets-minified.js", function()
{
var treeData = new buckets.MultiDictionary();
$.each(data, function(i,val)
{
if(typeof data == 'object')
{
$.each(val, function(j, childVal)
{
var dict = new buckets.Dictionary();
dict.set(val["NodeId"]["#text"], val["NodeText"]["#text"]);
treeData.set(val["ParentId"]["#text"], dict);
});
}
});
console.log(treeData)
return treeData;
});
}
This is on the html page that I call transformToStruct function :
var myGTP = new buckets.MultiDictionary();
$.ajax({
url: "http://frparlself6.dhcp.par.xxxx.corp:8000/com/sap/st/ltst/LTST_Backend/frontAccess/example.xsjs?structureId=" + structureId,
dataType : 'jsonp',
type:'GET'
}).always(function() {
var sXml = _JSONFromHANA.body
var xmlData = $.parseXML(sXml);
var xml = xmlToJson(xmlData);
var items = xml["soap-env:Envelope"]["soap-env:Body"]["n0:_-qte_-rfcReadStrucNodesResponse"]["EtNodes"];
myGTP = transformToStruct(items);
console.log(myGTP);
});
Any ideas?
treeData is the return value of an anonymous function that you pass as an argument to the function getScript. Your function transformToStruct doesn't actually have an own return value, so it's not surprising that it is undefined. Since getScript works asynchronously you could use a callback instead of a return value:
function transformToStruct(xmlData, callback)
{
var data = xmlData.item;
var myReturn;
$.getScript("buckets-minified.js", function()
{
var treeData = new buckets.MultiDictionary();
$.each(data, function(i,val)
{
if(typeof data == 'object')
{
$.each(val, function(j, childVal)
{
var dict = new buckets.Dictionary();
dict.set(val["NodeId"]["#text"], val["NodeText"]["#text"]);
treeData.set(val["ParentId"]["#text"], dict);
});
}
});
console.log(treeData)
callback(treeData);
});
}
Your function call would then look like this:
var myGTP = new buckets.MultiDictionary();
$.ajax({
url: "http://frparlself6.dhcp.par.xxxx.corp:8000/com/sap/st/ltst/LTST_Backend/frontAccess/example.xsjs?structureId=" + structureId,
dataType : 'jsonp',
type:'GET'
}).always(function() {
var sXml = _JSONFromHANA.body
var xmlData = $.parseXML(sXml);
var xml = xmlToJson(xmlData);
var items = xml["soap-env:Envelope"]["soap-env:Body"]["n0:_-qte_-rfcReadStrucNodesResponse"]["EtNodes"];
transformToStruct(items, function(result) {
myGTP = result;
console.log(myGTP);
});
});
But as mentioned in the comments, you should probably read something about asynchronous functions first.