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

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.

Related

How to show data outside of a subscribe scope/ how to use callback [duplicate]

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 3 years ago.
I want to show a list from an API call.
let url = 'api/list';
this.apiService.get<List[]>(url)
.subscribe((response) => {
this.list = response; // response has data
})
console.log(this.list); // no data shown
Because of async behavior the console always shows a blank list. How can I show the list with data outside of the subscribe scope. For clarification I need the list with data in the consoles position. I am familiar with the concept of callback. Do I need to use a callback function here? If yes, how can I achieve that?
The object the keyword this is pointing to is different in the places you are using it. So when you are setting this.list inside your callback function, you are setting the attribute list of your callback function.
One old skool way to fix this would be setting let that = this and then inside your callback function using that.list. By doing so you would be setting the attribute list of the keyword this that is one level above your callback function.
Hope it still makes some kind of sense.
Also look at Andrew Hills comment, it's full of logic :)

Cannot be able to access variable outside the function in angularjs when I call $http.get [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
$scope.order_details=function(index){
var temp_order_id=$scope.order_data[index].order_id;
$http.get('http://web.com/app/order_details/'+temp_order_id).then(function(response){
$scope.order_details11=response.data.data;
console.log($scope.order_details11);//Working Fine
});
}
console.log($scope.order_details11);//return undefined
This is an angularjs code on which I am working on when I console the array inside the $http.get(...) it is working fine but when I try to access that array outside the function it is returning undefined
By "Working Fine" do you mean it actually logged $scope.order_details11 to the console or do you mean the code just compiles fine?
If it is the later (code simply compiling), I think it's because you have not executed the callback $scope.order_details, only defined it, and hence the attributed order_details11 in $scope is non-existent.

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.

javascript variable value lost when outside object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
This may sound a newbie question but I'm having really hard time with variable scopes in Javascript.
I have the following JS snippet:
<script>
window.IDFVPlugin.getIdentifier(function(result){ uuid = result; });
alert(uuid);
</script>
I want to use the variable uuid anywhere in the script outside the window object. uuid returns the correct value only when inside the object and the value is lost when outside. So the alert above will log an undefined variable error.
You use a callback function. Result should be used inside of callback body. If you try to use it immediately after main function call - it will not be yet available
window.IDFVPlugin.getIdentifier(function(result){
uuid = result;
alert(uuid);
});

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

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]);
});

Categories

Resources