How to pass JQuery variable to a global one [duplicate] - javascript

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.

Related

Global Variable not updating through function [duplicate]

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"

How do I get value from Ajax function for jquery onclick function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a button that when I click on it , it will get data from my database , and display it on my text area based on the id.
JQuery
$('#verifyBtn').on("click", function() {
var exeOutput = checkOutput();
$("outputArea").html(exeOutput);
});
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
function getOutput(dataStr, flag) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
return data;
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
Through my servlet for getting from my database.
Servlet
exercisesModel outputModel = null;
try {
DBConnection db = new DBConnection();
outputModel = db.getExerciseById(request.getParameter("exNo"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().append(outputModel.getExpOutput());
EDIT: Upon clicking, i think there is data but my text area is not displaying it.
Since you're making an Asynchronous call you can't return an immediate response using return data;, but instead you could pass the selector then assign the result to your output element when the success callback is called:
<script>
$('#verifyBtn').on("click", function() {
checkOutput("outputArea");
});
function checkOutput(output_selector){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true, output_selector);
}
function getOutput(dataStr, flag, output_selector) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
$(output_selector).html( data );
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
</script>
NOTE : The passed flag parameter isn't used.
Hope this helps.
This block here:
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
try adding a return to the getOutput line
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
return getOutput(dataString, true);
}
By value i guess you mean the result of the call. You can find that in the parameter of the success handler.
success: function (data) {
//This is your result from server.
console.log(data);
return data;
}
Take a look at your JS console to see the results.

Passing/returning value to/from a function using ajax and callback function

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);

Why the function doesn't return the value? [duplicate]

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.

How to return an array from a Javascript Facebook API request?

Hopefully there is an easy way to do this and my Javascript skills are just lacking. I am wanting to call a function that will get some Facebook posts, add them to an array and return to use elsewhere. Current code is below.
function GetFaceBookStream(name, max) {
FB.init({ apiKey: 'removed for post' });
var lastDate = '2011-04-29Z00:00:00';
var faceBookArray = [];
var faceBookString;
FB.api("/" + name + "/feed", { limit: max, since: lastDate }, function (response) {
var sb = string_buffer();
for (var i = 0; i < response.data.length; i++) {
var post = response.data[i];
sb.append("<li class='facebook'>");
sb.append("<img alt=\"Facebook\" src='Images\\Carousel\\fbIcon.png\' />");
sb.append("<h4>FACEBOOK</h4>\n");
sb.append("<div class=\"from-name\">" + post.from.name + "</div>");
sb.append("<div class=\"time\">" + post.created_time + "</div>");
if (post.message != undefined) {
sb.append("<div class=\"message\">" + post.message + "</div>");
}
sb.append("</li>stringSplitMarker");
}
faceBookString = sb.toString();
faceBookArray = faceBookString.split('stringSplitMarker');
});
return faceBookArray;
}
I realize this set up won't work due to variable scope in Javascript, but this is basically what I'm trying to achieve. Any help will be greatly appreciated!
You're making an asynchronous AJAX request.
The callback only runs after your code finishes.
You need to pass the data back using a callback.
For example:
function GetFaceBookStream(name, max, callback) {
...
FB.api(..., function(response) {
...
callback(something, else);
});
}
You can call the function by supplying a callback to receive the response:
GetFaceBookStream(name, max, function(param1, param2) {
//This code runs later and can use the response.
});

Categories