Getting a Javascript variable out of a $.get statement [duplicate] - javascript

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.
EDIT: Please feel free to delete, I have found an appropriate answer in the duplicates mentioned above. Apologies.
I have the following code, and can't seem to dig the variables out correcly:
$('#button').click(function() {
alert(getRemaining(0));
}
function getRemaining(i){
var x;
$.get('files/remaining.txt', function(file){
x = file.split(",");
});
return x[i]
}
My alert just keeps coming out as undefined. What am I doing wrong?

the .get that you run is an asynchronous function. This means that execution of your code will continue on past it BEFORE it completes. The callback function that you pass into .get will be called once it is finished (this is the main reason for providing a callback).
This code will alert once the .get has returned.
$.get('files/remaining.txt', function(file){
x = file.split(",");
alert(x[0]);
});

Related

global variable in javascript not working; loses data [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
var feed;
$.getJSON('short.json', function(data) {
feed = data.items;
console.log(feed);
});
console.log(feed);
I have this short code written above. I am expecting feed to be a global variable but once it comes out the function, it's undefined again. It prints out an object when inside. What am I doing wrong?
Thanks for the help.
The reason is that the getJSON() call is asynchronous. It won't run until AFTER the second console.log();

Jquery GET in plain javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I call my_function on form submit. The function looks inside a text file for the number entered by the user in my_input. If this number does not exist, the function pops an alert and should stop form submit.
My problem: the alert is shown, but when I close it, the form gets submitted. My problem is similar with this thread: How do I return the response from an asynchronous call?
One of the solutions there is to do the GET in plain javascript. Can someone help please? This is too advanced for me.
function my_function() {
$.get("http://www.example.com/file.txt", function(contents) {
var my_number = document.getElementById("my_input").value;
var hasString = contents.includes(my_number);
});
console.log(hasString); // **ALWAYS RETURNS UNDEFINED**
if (hasString == false) {
alert('Number does not exist in text file!');
return false;
}
}
hasString is a local variable of the callback function provided to $.get as second argument. This is why it's undefined outside said function. Note just moving the variable declaration to the outer scope won't fix the problem, as the callback function will be executed after the check hasString == false anyway (it will be executed when the get request finishes).
Answering your question more directly: either perform the get request synchronously (and properly declare the variable in the scope you need to use it) or restructure your code to use the information retrieved by the get request only inside the callback. Read the post #abc123 mentions for more information.

How to get a value from a callback? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have this line of codes:
let message = channel.consume(queue, msg => {
console.log('Return this in the "message" variable', msg.content);
});
When I tried to log the value of message, it does not equate to msg.content but it gets the value from the return of consume method. What's the workaround in order for me to get the right value from the callback.
Thanks
var message;
channel.consume(queue, msg => { message = msg.content; });
Not really sure what you're asking, but are you trying to set message within the callback? If so, see above.
You cannot "return" the value of the callback. Also, there's little point in doing so since the line after that code will execute before the callback has even executed.
While it's not "returning" the value, you can use a Promise.
If you can transpile from ES7, you can use async-await which allows you to call asynchronous functions using synchronous-looking code within an async function using await.

Trying to access a variable inside a jquery function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to access a variables inside a $.post jquery method. The code I have so far is below:
var fromDatabase;
$.post( "../read.php", function( data ) {
fromDatabase = JSON.parse(data);
console.log(fromDatabase); //this works fine
return fromDatabase;
});
console.log(fromDatabase); // but this gives me 0.
I am trying to get the from database variable so i tried to declare it outside the function to no avail.
Thank you.
You can't - you must continue program execution from within the callback, not immediately after the asynchronous $.post call.
You cannot return from an asynchronous function, that's the nature of asynchronicity. Instead, after your value is available (the callback function is called) you must work with the data within the scope of that function.
Perhaps a good starting point would be some Ajax tutorial. If you want more, simply google for JavaScript async.

Ajax .responseText is available in alert but does not get saved in variable or return [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
var response_var=""; // Added this line for debugging
ajax.onreadystatechange=function()
{
if(ajax.readyState==4 & ajax.status==200)
{
response_var=(ajax.responseText);
alert(ajax.responseText); // This alerts properly (some text).
return (ajax.responseText); // This is returning as undefined
}
}
return response_var; // This is empty if I add the line 1, if not in console it gives error response_var is not defined.
Why does not the response is getting stored in the variable or returned? I guess the scope of response_var ends within the onreadystatechange function so I tried return. But the value is undefined.
Ajax function always work out of sync with normal code flow ,hence the name "Asynchronous JavaScript and XML" .For Ajax required events you should not rely on return ,rather do your task immediately when you get your response from AJAX.

Categories

Resources