Scope of Javascript Variable [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
return from a function ajax
JavaScript asynchronous return value / assignment with jQuery
How do you output the data variable to the second alert statement.
$.post("index.ajax.php", { lookup:value },
function(data) {
alert(data)
test = data;
})
alert(test)
Or would it be possible to do something like this?
function confirm_search(input) {
$.post("index.ajax.php", { lookup:input },
function(data) {
$("#temp").val(data);
})
}
var test = confirm_search(value);
alert(test);

You can't.
AJAX is asynchronous. The response is not available until some time later.
The jQuery.post call will begin the AJAX request, and return the jqXHR object which is handling the request. The script will continue to be executed (alert(test) will fire next), and then some time later when the AJAX request has completed (i.e. the HTTP response is received), the callback:
function(data) {
alert(data)
test = data;
}
will be executed.

If you are strict with scenerio, define test variable in global scope, in that way you can use it anywhere in your code.

Try this way :
var test;
$.post("index.ajax.php", { lookup:value },
function(data) {
alert(data)
test = data;
})
function alertTest(){
if(test != undefined) {
alert(test);
clearInterval(t);
}
}
var t = setInterval(alertTest, 1000);
You will get test value when ajax request is completed and test is assigned

Related

Calling variable within jquery function from outside [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)
Closed 7 years ago.
var test = null;
$.get("/zeWebsite.php?blarg=421", function(data){
test = data.trim();
});
alert(test);
I always thought declaring the variable from outside the function before hand gave access to the variable even if called within the function. However, my test variable is still alerting as null.
It is likely an order issue as the $.get function is asynchronous. The callback of the get is not being run until after the alert has already fired.
The alert is being run BEFORE the get has completed. You need to make sure the get is complete before alerting by triggering alert within the callback.
Try:
var test = null;
$.get("/zeWebsite.php?blarg=421", function(data){
test = data.trim();
alert(test);
});
or
var test = null;
$.get("/zeWebsite.php?blarg=421", function(data){
test = data.trim();
outside();
});
function outside() { alert(test); }
it just not assigned yet..
You can simple wait for it:
var test = null, inprocess = true;
$.get("/zeWebsite.php?blarg=421", function(data){
test = data.trim();
inprocess = false;
});
var wait = setInterval(function(){
if (!inprocess) {
clearInterval(wait);
alert(test);
}
}, 500);
But this code is awful. Much better to trigger callback directly:
var test = null;
$.get("/zeWebsite.php?blarg=421", function(data){
test = data.trim();
anyactionwithtest(test);
alert(test);
});
Or use something like jquery deffered promise:
var test = null;
$.get("/zeWebsite.php?blarg=421", function(data){
test = data.trim();
}).done(function (data){
// data also accessible here as is
alert(test);
});
This is because you are using the variable before the get statement execute completely.
Test will get the value when the get function callback call.
If you place alert in get function then it will call at last.

Return data from an AJAX request [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have json data in file that I want to read. It prints to the console.log the correct file data.
How do I get that data into variable x? When I run the code, x is undefined.
function getData() {
$.get('data/APPFeaturesMetaData.json', function (data) {
console.log(data);
return data;
});
};
var x = getData();
It's an asynchronous call, So the var x = getData(); runs before the AJAX request is complete.
The answer is, use deferred it looks something like this:
var request = $.ajax(
{
url: url,
});
// When the request is done, do something with data.
request.done(function (data) {
console.log(data);
});
In your case, it's different if you want to return data, you will have some scoping problems. the fix is really easy, Here's what your final code will look like, I will explain stuff in the comments:
function getData() {
// This is where we store the data.
var myData;
// This will refference current object.
// You need to keep the refference of this object.
var self = this;
$.get( 'data/APPFeaturesMetaData.json' ).done(function(data) {
// the keyword `this` will not work here, because you're inside an AJAX callback.
// When you say `this`, you're actually refferencing the AJAX object
// And not the getData object.
self.myData = data;
});
return myData;
};

jQuery AJAX Race Condition [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I've seen similar questions asked on SO but no quite my problem.
I have something like
var x = 5;
if( some condition ){
$.ajax({
url:"...",
success: function(response){
x = response.x;
}
}
}
some other logic
use x variable
What is happening is the thread executing the JS gets to the logic that uses x before the asynchronous task comes back.
Normally I would just put whatever logic inside the success function but I need the logic to happen regardless of whether or not the condition is met and I don't want to replicate code. Anyone have any suggestions? Should I just async to be false?
Thanks!
async false would be one way to go about it since you want the value returned by x to be used if the condition is true.
You could also use promises.
var x = 5;
var ajaxCall;
if(some condition) {
ajaxCall = $.ajax({
url: "...";
});
}
function usingx(x) {
//Add your logic
}
if(typeof(ajaxCall) === 'undefined') {
usingx(x);
} else {
ajaxCall.done(function(data){
usingx(data.x);
});
}
It is either going to async false or you have call the function in two cases, one case where it can execute without waiting and the other in which it has to wait.
A bit more complicated way would be to wait till Ajax gets completed and then run the function.
var x = 5;
var isCallMade = false;
if(some condition) {
isCallMade = true;
ajaxCall = $.ajax({
url: "...";
}).done(function(data){
x = data.x;
}).always(function(){
isCallMade = false;
});
}
function useX() {
if(isCallMade) {
setTimeout(useX, 100); //Wait for ajax call to finish
} else {
//logic using x
}
}
Use the always callback.
if( some condition ){
$.ajax({
url:"...",
success: function(){ // BTW, as of jQuery 1.8 this is referred to as "done"
// Success specific code
},
always: function() {
// Code that always executes regardless of success or failure
}
}
}
JQuery also has an fail() callback in case the Ajax fails. I'd just put the logic in both cases. (abstracted into a function)
Check out this question.
jQuery: Handle fallback for failed AJAX Request
**Revision
$.ajax's complete() method runs after an ajax call no matter what. Sounds perfect.
http://api.jquery.com/jquery.ajax/

JavaScript variable not being set [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Variables set during $.getJSON function only accessible within function
(6 answers)
Closed 8 years ago.
I have a small piece of js that pull some data from via ajax.
solarSystem = "test";
$.getJSON( "ajax/getLocation.php", function( data ) {
var items = [];
$.each( data, function( key, val ) {
solarSystem = val;
});
});
alert(solarSystem);
val is being set but its not outputting to the alert if i put the alert in that function it works. I assume its something to do with scope but im new to js if anyone can point me in the right direction it would be much apreciated.
While JavaScript is single-threaded, it can perform tasks asynchronously, i.e. function calls do not necessarily complete before the next line of code. AJAX (asynchronous JavaScript and XML) calls do just that. For example,
console.log("starting")
$.getJSON("path/to/resource", function (data) {
console.log("data retrieved")
})
console.log("finished")
The above code will most likely print starting and finished before it prints data retrieved. This is because $.getJSON is asynchronous. It requests a resource on a server somewhere, waits for a response, then calls the anonymous function provided as a callback, i.e. the function (data) { /* etc */ } part.
In your case, the callback function is running after alert, even though it is written above it in your code. If you want to alert(solarSystem), you'll need to place that inside of your $.getJSON call to ensure it is processed correctly:
solarSystem = "test"
$.getJSON("ajax/getLocation.php", function (data) {
var items = []
$.each(data, function (key, val) {
solarSystem = val
})
alert(solarSystem)
})
Anything inside the $.getJSON cannot access anything outside without some changes to your code. You need what is a called a callback function, and the problem is due to variable scoping.
solarSystem = "test";
function setSolarSystem(newSystem){
solarSystem = newSystem;
alert(solarSystem);
}
$.getJSON( "ajax/getLocation.php", function( data ) {
var items = [];
$.each( data, function( key, val ) {
setSolarSystem(val);
});
});

How can I alert the contents returned from this 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 have a function that returns JSON information. I want to be able to store that into a variable and then use alert and the variable name to display the content returned from that function. Here is my code:
var getStuff2 (function (num) {
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://catholic.com/api-radio/' + num) + '&callback=?', function(data) {
//console.log(data.contents);
//$('#response').text(data.contents);
obj = data.contents;
//alert(obj);
}];
return data.contents;
});
});
function getData(){
getStuff2(6387);
}
getData();
alert(getStuff2);
You have to put the alert inside of the callback handler for the AJAX function. AJAX calls are asynchronous which means that if you do something like this, the return won't work in the order you expect:
function getData() {
doAjax(function(data) {
obj = data.contents;
});
alert(obj);
}
You see, the AJAX call will return when it returns, and all of the code after it will just keep executing while the AJAX call is still waiting on a response.
So what you have to do is this:
function getData() {
doAjax(function(data) {
obj = data.content;
alert(obj);
});
}
I assume, that data.contents is a object, so your alert output will look something like [object object], so you just can't alert the content.
To make it globally available just store the content in a gloabl variable.
var result;
var getStuff2 (function(num) {
$.getJson(url, function(data)
result = data.contents;
});
}),
asynchronous functions cannot return values. Instead you need to explicitly do something with the value from inside the AJAX callback.
function getStuff(num, onContents){
$.getJSON(..., function(data){
//call the oncontents callback instead of returning
onContents(data.contents);
});
}
//when calling getstuff, pass a function that tells what to do with the contents
getStuff(6387, function(contents){
console.log(contents);
});

Categories

Resources