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.
Related
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);
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 have a simple script to get a PHP session user id into a javascript file. Yet when I try to simply alert the user id it says undefined?
As shown in code I have tried with simple alert to check the data coming back from the script and it is correct.
var user_id;
$.get( "/ajax/actions/getUserId.php", function( data ) {
// alert(data); <-- this works correctly
var user_id = data;
});
alert(user_id);
Is there a better way to do this?
The PHP file accessed (getUserId.php) is simply:
session_start();
echo $_SESSION[user_id];
Ajax is asynchronous, so the last alert will be executed before the callback function of ajax is called.
You should use:
$.get( "/ajax/actions/getUserId.php", function( data ) {
var user_id = data;
alert(user_id);
});
Ajax is asynchronous by default.
In your snippet the code goes through the following steps:
Define variable called user_id in the global lexical scope
Make GET ajax request to /ajax/actions/getUserId.php
Alert the value of the variable user_id which is undefined (by default, you haven't set it any value).
At given point the ajax request is successfully completed, your callback gets invoked so:
You define new variable called user_id, in the lexical scope of your callback
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm playing around with using the forecast.io API to (eventually) make something that will email me every day about the weather in my area. When I make a request to the API, it gives me a JSON object with all the information in it. I'm using JavaScript and PHP write this. Here is the code I have so far (it's a bit messy right now):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var latitude = "42";
var longitude = "-71";
var coordinates = latitude + "," + longitude;
var forecast;
$.ajax({
url: "<?php echo $_SESSION['url'] ?>42,-71",
type: "GET",
dataType: "jsonp",
crossDomain: true,
jasonpCallback: 'blah',
success: function(data) {
forecast = data;
console.log(forecast.daily.summary);
},
error: function() {
console.log("This failed.");
}
});
//**********************************
document.write(getDailySummary());
//**********************************
function getDailySummary() {
var summary = forecast.daily.summary;
return "<p>" + summary + "</p>";
}
</script>
Right now, the $.ajax() statement runs successfully, and the forecast summary is logged in the console. However, the getDailySummary() doesn't run so well. I get the following error when I run this:
Uncaught TypeError: Cannot read property 'daily' of undefined index.php:42
getDailySummary index.php:42
(anonymous function) index.php:37
Rain on Thursday and Friday; temperatures rising to 85° on Saturday. index.php:28
This makes it sound like forecast is undefined. My initial thought is that it has to do with scope, but I've tried fiddling around with all sorts of things, including defining forecast as window.forecast, but I always get this error. Where am I going wrong?
Ajax is Asynchronous.
The line below ajax method executes before the data is populated. Call that function inside the success handler
So when you try to access the forecast object it is still undefined.
success: function(data) {
forecast = data;
console.log(forecast.daily.summary);
getDailySummary(forcast);
},
And never use document.write to write to your HTML. Try appending the data to some element on the page.
The line:
document.write(getDailySummary());
gets called before the ajax call successfully completes, which is why you get the error as forecast has not yet been assigned.
Ajax is asynchronous
This question already has answers here:
console.log() async or sync?
(3 answers)
Closed 8 years ago.
Can anyone elaborate on what might be going wrong? I have no real clue on what to look for at this point.
sample code:
$.ajax({
url: uploader.fileupload('option', 'url'),
context: uploader,
success: function(response){
//logging uploader
console.log(uploader);
//logging this --> logs the same as logging uploader
console.log(this);
//loggin response --> clearly shows a context attribute holding the correct data for this response
console.log(response);
//logging response.context --> shows undefined
console.log(response.context)
var done = uploader.fileupload('option','done');
done.call(this, null, response);
},
dataType:"json"
})
I'm not used to working with the context attribute in $.ajax() call and i'm suspecting this functionality to cause my issue.
The snippet causes issues in my code some time after the ajax call. I'm pretty sure this has nothing to do with ASYNC problems, since problem allready exists way back in the actual success-callback of the original ajax-request.
I've disabled php-headers which were sent, but it remains the same. I tried this based on another topic which implies something could be wrong with my headers.
I've also disabled the dataType attr in $.ajax() but then my response isn't recognised as being json.
Any help or tips on how to debug are much appreciated!
UPDATE:
removing the context attribute in the ajax-call does solve the issue.
But why does it get appended to my response object (or at least seems to be appended) when console.logging()
I'm not sure if this is your problem because the question itself should be better specified. But looking at the title, it seems the plain old problem with console.log()being asynchronous and passing by reference.
When you call console.log(object) the object is kept as a reference and not printed immediately. After some time, when the logging actually happens, the object may be in a different state (for example as in this case, it may have an attribute).
On the contrary when you log obj.property the call is synchronous and that property is not yet defined.