This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am working on a Javascript / JQuery project that requires that I get data from another website. I use the following JQuery code to achieve this:
var user = "Bob";
url = "https://api.example.com/api/" + user;
$.get(url, function(data){
profiles = data;
});
alert(profiles);
For some reason when I run the code I get this Error Message:
Uncaught ReferenceError: profiles is not defined
But when type "profiles" in the google chrome javascript console, I see my target data. What am I doing wrong?
Thanks- Evan
Are you in 'use strict' or an es6 module ? it sounds like it
You need to explicitly declare the variable
var user = "Bob";
// this was not really the problem
var profiles;
url = "https://api.example.com/api/" + user;
$.get(url, function(data){
profiles = data;
// run your alert here
alert(profiles);
});
//this is the problem. The above callback function runs asynchronously,
// after the data has been fetched which can take some time
// code from this point on runs synchronously, before the request to the server
// hence 'profiles is undefined'
alert(profiles);
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)
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I've been messing around with this Wikipedia node module in bash and I'm having some trouble saving the response to a variable. I can use console.log(response) to see the complete response but I can't get it to stick to a variable.
I tried maybe looking at the type of response but it just returns undefined. Any ideas?
var wikipedia = require("node-wikipedia");
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
console.log(typeof response);
});
Ideally I'd like to assign the response which has an html object to a variable and then use cheerio to get pieces of the html object with jQuery selectors, but I believe I need to at least get it in to a variable first, right?
This is part of the response.
{ title: 'Clifford Brown',
redirects: [],
text: { '*': '<div class="hatnote">For the scrutineer for the Eurovision Song Contest, see Clifford Brown (scrutineer).
Edit/Fix
I was able to get this to work based on #idbehold's comments. Everything needed to be done in the call back so instead of calling the variable after the request, I returned it in the callback like this, which gave me access to the variable outside of the function.
var wikipedia = require("node-wikipedia");
var data;
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
data = response;
})
There are many, many questions of this sort which appear on StackOverflow, and they all stem from not understanding the asynchronous nature of AJAX. Your code does not block at the .data() call to wait for the server to respond. Any lines of code that run after that call will run immediately, whereas the code inside your callback function will runs at some point in the future, after the data is returned from the server. Anything you do in response to getting the data must happen in that callback.
var wikipedia = require("node-wikipedia");
wikipedia.page.data("Clifford_Brown", { content: true }, function(response) {
console.log(typeof response);
// do something with the response here
});
// any code here will run before the above callback is invoked.
// don't try to do anything with the response here.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am having a problem setting some global variables to use outside of the script that I am writing. I believe that I am setting them correctly but they don't seem to be cooperating. My console output is always an empty string, where as they are supposed to be defined inside the primary calling function of the demo web page. All of the other data seems to be working fine, if I print it out without setting it to a variable then it works fine. However I need the variables so that I can call them outside of this script. Any ideas?
var latitude = "", longitude = "";
$(document).ready(function() {
$.ajax({
dataType: "json",
url:"http://api.geonames.org/searchJSON?q=Atlanta&maxRows=10&username=Demo"
}).then(function(data){
console.log(data);
latitude = data.geonames[0].lat; <---Variables are supposed to be set here
longitude = data.geonames[0].lng; <----Variables are supposed to be set here
$('.map-Latitude').append(data.geonames[0].lat); <----Works well
$('.map-Longitude').append(data.geonames[0].lng); <----Works Well
});
});
console.log("Latitude is: " + latitude); <---- prints out an empty string
console.log("Longitude is: " + longitude); <---- prints out an empty string
I cant seem to get this to work, I feel like I am setting the variables properly but they don't seem to be working well. Thanks!
Your $.ajax() call is asynchronous. The results of the call are not available until the HTTP response is received by the browser.
Put your console.log() calls inside the .then() function.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have been working on this for the past 2 hours. I am getting the error, SyntaxError: Unexpected token u when I try to parse a GET request using a function. But I perform the same code one line at a time it works fine.
I noticed that as soon as I create an object its readyState is 1, but right after I save it and wait a second the readyState changes to 4 then it parses fine.
I thought that maybe the XmlHttpObject I am pulling just needs to communicate to the server after the object is already on my computer, like maybe it is not done pulling all information and once the information pull is complete it turns it to 4. As a result of this realization I tried to use the timeout function to wait a few seconds then try to parse it, but I still couldn't get it to work!
Here is my code:
function pullData(){
var obj = $.get("https://api.parse.com/1/classes/chats");
var object_array = JSON.parse(obj.responseText);
return object_array
}
function pullData(callbackFunction)
$.get( "https://api.parse.com/1/classes/chats", function( data ) {
var object_array = JSON.parse(data);
callbackFunction(object_array);
});
}
JavaScript ajax calls are asynchronous, so u can't get the result at next line code after you perform get request, because get request is executed in background.
JQuery has a great documentation to look how to write ajax requests. http://api.jquery.com/jquery.get/
Why don't you try
function pullData(){
$.get("YOUR_URL")
.done(function(data) {
var object_array = JSON.parse(data);
return object_array
})
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I want to load a data that I got from Jquery.get into the variable in another function. The way I have tried is
function setPolicy(){
jQuery.get('/webapp/myProject/getPolicy', function(policy) {
console.log(policy + " Policy"); //Just for Observation
}); }
and I want to load the data which is now stored in the Parameter Name "policy" into another variable in another function like the following
function loadAPI() {
var policy = setPolicy();
console.log("The policy is " + policy);
The result Shows in the console is just
The policy is
which mean the variable policy is not receive the data from the function.
What I would like to ask is How can I load the data from function "setPolicy" into the variable Name "policy" in another function calls "loadAPI" as a string? Thank you in advance.
You need to return the fetched value. Try to add this stmt in your code -
$.get('URL', function(data) {
$('.result').html(data);
return data;
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am creating an object in javascript:
var t = null;
$.getJSON('http://localhost:53227/Home/GetData', function (data) {
alert(data);
t = data;
});
alert(t);
When I alert data, I get an object back.
When I alert t, it's null.
Can you please guide, how to set "t" to the returned data?
This will work as expected - the issue is not that t is not set, it's that you're doing alert(t) before the getJSON callback is executed. Try doing alert(t) immediately after t = data;
In other words, here's your current order of operations:
Set t = null
Call server script
alert(t) --> t is still null!
(some amount of time later) receive JSON response
alert data
set t = data
...as you can see, at step 3 't' will still be null. Try this instead:
var t = null;
$.getJSON('http://localhost:53227/Home/GetData', function (data) {
alert(data);
t = data;
alert(t);
});
Cheers