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
Related
For as simple as this should be, I have no idea what I am doing wrong. I'm attempting to fetch a local text file and store it in a variable, but regardless of the method (fetch api, $.get and ajax) I use, I always get undefined.
$(document).ready(function() {
var fileConfiguration;
$.get( "Configuration.h", function( data ) {
fileConfiguration = data;
});
document.getElementById("demo").innerHTML = fileConfiguration;
});
The data variable is properly fetched, I can use alert or console.log and see the contents correctly. When I assigned it to a variable though, it's undefined. I imagine this has something to do with it being an asynchronous callback, but can't figure out the problem.
As you and #charlietfl have pointed out the AJAX request is asynchronous which means that the last statement in your code is executed before there's a response, hence fileConfiguration is still undefined.
Therefore the best place to do the assignment is inside the callback like so:
$(document).ready(function() {
$.get( "Configuration.h", function( data ) {
document.getElementById("demo").innerHTML = data;
});
});
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)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
I have a following piece of javaScript code:
var ws_path = "x";
$.get('ws.config', function(data) {
ws_path = data;
alert(ws_path); //alert 1
},
'text');
alert(ws_path); // alert 2
// output = alert 1 = value of data
// alert 2 = x
I have a confusion' why it is behaving like this?
It is because alert(ws_path); gets executed before the content is get from server for ws.config file. You need to write the code in success function of get to ensure that variable is modified after get request.
jQuery.get
The second alert is fired before the $.get request is completed.
The important point here is:
$.get('ws.config' ....
is a kind of ajax call and it takes some time to get the actual value from the server, and that anonymous function there is a callback function which gets called when the ajax call receives the response.
Here in your code if you want to have a ordered scenario you can do this:
var ws_path = "x";
$.get('ws.config', function(data) {
ws_path = data;
alert(ws_path);
continueScenario();
}, 'text');
function continueScenario(){
alert(ws_path);
}