Making $.get assign something to a variable [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm trying to use $.get() to retrieve data from a server, and assign it to a variable to work with it. For example:
$.get('htmllink', {}, function(results){
//do stuff here
});
var morestuff = ; //$.get() data goes here
The problem is, I can't get anything to work outside the rounded brackets. Everything is treated as internal variables or something. What am I missing?

You need to do all of your processing inside the callback function. This is because the call to $.get only starts an asynchronous request, and then the next line (var morestuff = ...) is executed after the request starts, but before it has completed.
$.get('htmllink', {}, function(results){
//do stuff with results in here
});

The problem here is that the $.get request is asynch (Ajax), so there is a timing issue here. The
var morestuff =
will run before the Ajax call returns, so you won't have the value to assign.
You have to interact with the result of the ajax request in the call back to have access to it
$.get('htmllink', {}, function(results){
//all code that depends on results must run inside here
});
//you can't execute code here that depends on the Ajax call

Related

Setting a function variable from jQuery AJAX result [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm doing a GET request with jQuery inside of a function and trying to set a variable declared earlier in that function with the result. However, it comes up as undefined. Am I missing the concept here? How can I make something like this work? Thanks.
function doSomething1() {
var x;
$.get( window.location.href, { q: 'stuff', q2: $('input').val() }, function(data){
// value shows up
console.log(data);
x = data;
});
return x;
}
function doSomething2() {
// comes up as undefined.
console.log(doSomething1());
}
doSomething2();
This is a fault of the asynchronous effect of $.get() requests. You are returning x before the get has a chance to do anything. It takes a while to wrap your head around async functions.
The order of events is as follows:
doSomething2() calls doSomething1()
doSomething1() defines x without a value begins the GET request, and returns undefined.
doSomething2() logs the returned x value
The GET request finishes and processes its success function

Get Data out of JQuery Function $.getJSON [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 8 years ago.
This is more of a basic JQuery/Javascript question: How do I get data out of the getJSON function?
The following code works great until the function ends. I have several getJSON that will need to run one-after-the-other and I would like to avoid nesting them if I can:
//Using the Web API to pull all the information out for the current ORG ID
$.getJSON('http://localhost:8081/dhis/api/organisationUnits/' + vuCurrentFacilityID + '.json', function (data) {
//alert(data.message);
console.log(data);
vuCurrentFacilityName = data.name;
vuParentFacilityID = data.parent.name;
});
alert(vuCurrentFacilityName); //does not work
What Gotcha* am I missing?
This question is very similar to the following.
if you call $.getJSON() you are entering an asynchronous context, and everything after it gets executed immediately. So your alert is called before the server responds.
use deferreds instead
var promise = $.getJSON( ... );
promise.done(function() {
alert("yeah");
});

Get global var from function after $.get() jQuery [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 this code
var base_url = 'http://api.zxc.loc';
var questions = [];
function get_question(){
if(!questions.lenght){
$.get(base_url + '/api/questions', function(data){
questions = data;
console.log('get_question', questions); // GOOD, return [Object, Object ... etc ... ]
}, 'json')
}
console.log('get_question_2', questions); // BAD return empty array []
/* var question = questions[0];
delete questions[0];
return question; */
}
How you can see, in $.get questions variable not empty, but after $.get, questions is empty!
Why? Thanks
This is how AJAX works. In your code get_question_2 will be logged before get_question. Once an ajax call is made, the code proceeds past it (to get_question_2). Then one the ajax call is returned, the code inside your function (namely get_question) will be executed.
To summarize, the log with get_question_2 is being called as soon as the ajax call is finished being made and BEFORE the ajax call returns with the data.

javascript assignment of a string issue [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
Im having an issue assigning a string to a variable and then returning it. It sounds simple and should be but im completely lost as to why what is happening is happening.
My code:
function drawpills() {
var picid;
$.post('js/fetchdata.php', function (data) {
var clock = document.getElementById('clock');
clock.innerHTML = "<img src='images/clock/pill.png' alt='pill_image' id='pillpic" + data + "'/>";
picid = "pillpic" + data;
alert(picid); //if i run it here i get pillpic31 which is what i want
});
alert(picid); //if i run it here i get undefined which is not what i want and which is what is being returned
return picid;
}
I highlighted the issue with comments on the respective line. Any help is appriecated.
Suggest you read through the linked article in comments.
What you need is something like this:
function drawpills(callback){
var picid;
$.post('js/fetchdata.php', function(data){
var pcid = data; // process pcid here
callback(pcid);
});
}
The problem is the asynchronous behavior of AJAX. When the AJAX response is sent, it moves onto the next statement, whether or not the call has finished executing. You can now do one of two things. You could either make the AJAX synchronous, which will probably break the timing of events on the page, or you could create a callback to be executed when the AJAX call is completely finished.
$.post callback is asynchronous function,so:
function drawpills(){
var picid;
var callback = function(data){
var clock = document.getElementById('clock');
clock.innerHTML="<img src='images/clock/pill.png' alt='pill_image' id='pillpic"+data+"'/>";
picid="pillpic"+data;
alert(picid);
}
$.post('js/fetchdata.php', callback);
//picid is undefined,because callback is running until server response data.
//unless you using synchronous request
alert(picid);
return picid;
}

Set variable inside AJAX callback function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I need able or disable a click event depending on the server result. I have the following funcion using jquery:
$("#button").click(function(){
var validated = true;
$.ajax({
url: "/Foo",
type: "POST",
success:function(data){
// alert(validated); ----> true
if(data){
validated = false;
// alert(validated); ----> false
}
}
});
// alert(validated); ----> true
return validated;
});
In the above code, always return true. I think the problem is that I set wrong the global variable validated. I have read this post and this but does not work for me. What am I doing wrong?
The problem is, that the AJAX call happens in a separate "thread" than the rest of the function. Thus, the thread with the click event runs on its own, does the AJAX call which is done ASYNCHRONOUSLY, and then returns. The AJAX thread never has the time to modify the validated var - the click handler has already returned.
The best way to solve this would be to make a callback from within the AJAX thread, or disable the element you want inside the AJAX thread itself, rather than returning a result to another function, which will then modify your button in another thread.

Categories