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"
Related
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));
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 7 years ago.
I'm trying to retrieve data from JQuery function and pass it into global variables to use with Google Maps. These variables have to stay global, otherwise Google Maps don't work with them. I manage to get all data that I need from AJAX url and it logs perfectly but only inside Jquery function. If I log it outside of it, it's undefined. Is there anyway to pass those values to global variables?
function displayMarkers() {
var latlng = new google.maps.LatLng(latitd, longtd);
var name = titleName;
createMarker(latlng, name);
}
var latitd;
var longtd;
var titleName;
$(document).ready(function() {
$('#earthquakes').click(function() {
getQuakes();
});
function getQuakes() {
$.ajax({
url: 'http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=' + yesterDate + '&endtime=' + displayDate,
success: function(data) {
console.log(data);
$.each(data.features, function(key, val) {
var coord = val.geometry.coordinates;
locationD = {
latd: coord[0],
lngd: coord[1]
};
latitd = locationD.latd;
longtd = locationD.lngd;
titleName = val.properties.title;
console.log(latitd, longtd);
console.log(titleName);
});
}
});
}
});
Your code should be like this
var latitd;
var longtd;
var titleName;
$(document).ready(function () {
$('#earthquakes').click(function () {
getQuakes();
});
});
function getQuakes() {
$.ajax({
url: 'http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=' + yesterDate + '&endtime=' + displayDate,
success: function (data) {
console.log(data);
$.each(data.features, function (key, val) {
var coord = val.geometry.coordinates;
locationD = {
latd: coord[0],
lngd: coord[1]
};
latitd = locationD.latd;
longtd = locationD.lngd;
titleName = val.properties.title;
console.log(latitd, longtd);
console.log(titleName);
//Call this function to display here after success ajax
displayMarkers();
});
}
});
}
function displayMarkers() {
var latlng = new google.maps.LatLng(latitd, longtd);
var name = titleName;
createMarker(latlng, name);
}
Add an async:false to your ajax request.
I'm trying to read p_info array returned from the function getproductInfo containing a ajax call but I'm getting undefined value. I'm using a callback function to achieve this but still doesn't work. Where am I wrong?
$(document).ready(function() {
function successCallback(data)
{
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
console.log(product_info); // Correct: shows my product_info array
return product_info;
}
function getProductInfo(prodId, successCallback) {
$.ajax({
type: "POST",
url: "getProductInfo.php",
data: "id=" + prodId,
dataType: "json",
success: function(data) {
var p_info = successCallback(data);
console.log(p_info); // Correct: shows my product_info array
return p_info;
},
error: function()
{
alert("Error getProductInfo()...");
}
});
return p_info; // Wrong: shows "undefined" value
}
var p_info = getProductInfo(12, successCallback);
console.log(p_info); // Wrong: shows an empty value
});
The code should speak for itself. But basically, you cant return an upper-level function inside a function. You must set a variable to be used to return after the ajax is submitted.
//This makes the p_info global scope. So entire DOM (all functions) can use it.
var p_info = '';
//same as you did before
function successCallback(data) {
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
return product_info;
}
//This takes prodID and returns the data.
function getProductInfo(prodId) {
//sets up the link with the data allready in it.
var link = 'getProductInfo.php?id=' + prodId;
//creates a temp variable above the scope of the ajax
var temp = '';
//uses shorthand ajax call
$.post(link, function (data) {
//sets the temp variable to the data
temp = successCallback(data);
});
//returns the data outside the scope of the .post
return temp;
}
//calls on initiates.
var p_info = getProductInfo(12);
console.log(p_info);
I'm not quite sure why my code's output changes when I move the console.log() into the second AJAX call.
By splitting the three console.logs between the two AJAX calls, this code returns what I want (all productTitles with their productURLs and numProductTopics):
http://pastie.org/8067201
But after moving all three console.logs into the second AJAX call, this code returns the same productTitle and productURL every time with the differing, desired numProductTopics:
http://pastie.org/8067203
Could someone please explain?
This is because you have a for loop where you assign value to your variables and start an ajax call, which will get executed before your ajax success callback executes. So they will hold the value of that last iteration.
for (var i=0;i < results.data.length; i++) {
var object = results.data[i];
if (object.canonical_name && object.name) {
var productTitle = object.name;
productURL = "getsatisfaction.com/trinet/products/" + object.canonical_name;
jQuery.ajax({
type: 'GET',
url: apiBaseURL + 'topics.json?product=' + object.canonical_name,
dataType: 'jsonp',
success: function(results2) {
var numProductTopics = results2.total;
console.log(productTitle); //<-- this will have the value from last iteration
console.log(productURL);//<-- this will have the value from last iteration
console.log(numProductTopics);
}
});
}
You can also resolve it by enclosing the variables for each loop int the ajax call by making it a function invocation. bacically you want to lockin the variables as closure variables for each iteration.
for (var i=0;i < results.data.length; i++) {
var object = results.data[i];
if (object.canonical_name && object.name) {
var productTitle = object.name;
productURL = "getsatisfaction.com/trinet/products/" + object.canonical_name;
(function(productTitle, productURL){ //<-- Take the arguments
jQuery.ajax({
type: 'GET',
url: apiBaseURL + 'topics.json?product=' + object.canonical_name,
dataType: 'jsonp',
success: function(results2) {
var numProductTopics = results2.total;
console.log(productTitle);
console.log(productURL);
console.log(numProductTopics);
}
});
})(productTitle, productURL); //Lock in the variables here invoking the function call.
}
FIddle
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.