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.
Related
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 apologize for asking such a simple question, but googling "javascript or jquery first" just keeps giving me people asking which they should learn first.
Currently I have a couple lines of javascript, followed by a bit of jquery, followed by a bit more javascript. This is the part where it breaks down...
$.get("alliances.php", function(data, status){
console.log(data);
searchIndex = data.search(allianceName);
rawAllianceLink = data.slice(searchIndex-25,searchIndex);
});
console.log(rawAllianceLink);
After I carry this code out, the JQuery goes last and my console.log prints undefined. (Note, the console.log isn't the actual statement, I have more lines that need to go after this, it is just an example that it is performed out of order.) Was wondering if someone could clarify or explain how I can alter when each of these steps is carried out.
Simple ans:
Its simply because your $.get(... is an AJAX call. You have to log your data in callback handler.
$.get("alliances.php", function(data, status){
console.log(data);
searchIndex = data.search(allianceName);
rawAllianceLink = data.slice(searchIndex-25,searchIndex);
})
.done(function() {
console.log(rawAllianceLink);
});
Let's get a few things clear here. $.get() is a wrapper for $.ajax() in jQuery. The javascript being applied happens within the jQuery library.
Next, the $.get call is asynchronous meaning that the console.log(rawAllianceLink); likely will fire prior to the $.get() request completing, which takes some time to fetch the file and read the data.
The function(data, status) is applied to the data returned from alliances.php only after the request has fully completed. Within that callback function, it would seem as if you've properly applied the javascript methods that you intend.
If you need to fire further code after the callback execution occurs, then you should place it into a function and execute the function at the end, passing the rawAllianceLink as an argument, like so:
$.get("alliances.php", function(data, status){
console.log(data);
searchIndex = data.search(allianceName);
rawAllianceLink = data.slice(searchIndex-25,searchIndex);
process_request(rawAllianceLink);
});
function process_request(RAL){
console.log(RAL);
}
Now things will be fired in the proper order. You could also look into jQuery's $.defered, but that may be another beast, entirely.
What is happening in your code, is that, the jQuery "get" function is called, which sends a request to the server to retrieve some information at "alliances.php", but it just sends the request, it doesn't wait for a response, then it carries on with the console.log. At some later point, the browser gets the response back from the server, and when the browser gets a chance, it executes the code in the callback function. This kind of programming isn't unique to jQuery, it happens with event handler, timeouts, intervals, etc. in javascript, whether you use jQuery or not.
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 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 9 years ago.
This the data im getting from post is a simple object and the return value is always empty. Its logging to the console fine. any ideas?
function getTaskData(item){
var returnText = '';
$.post("index.php", {name: "getTaskData", pk: item.taskDataId}, function(data){
console.log(data);///Object {taskData: "Also - whats up with this?"}
console.log(data.taskData);///Also - whats up with this?
returnText = data.taskData;
},"json");
return returnText;
}
The code included in the block function(data) { ... is called a callback. It will be aynchronously called when the server's ajax call has finished. Whereas the return returnText will be called immediately.
Whatever you are going to do with the returntext (update DOM etc) will need to be done in the callback function