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;
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Im struggling with this js code for some reason. I can't access variables inside the ajax function.
I tried solving this by placing the "formatted" variable above the ajax function but I can't access it from inside. How do I solve this?
angular.module('ireg')
.controller("compoundSearchController", function(){
var vm = this;
vm.searchText = "Enter your search here...";
vm.compounds = getJSON();
function getJSON(){
var formatted = "initial";
console.log(formatted); // equals initial
$.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){
formatted = jQuery.parseJSON( result );
console.log(formatted); //equals the correct object
}})
console.log(formatted); // equals initial
return formatted;
}
console.log(vm.compounds); // equals initial
});
Asynchronous behavior of AJAX calls is the reason of difference between actual behavior and expected behavior.
Update your code to
var formatted = "initial";
$.ajax({url: "http://localhost:8080/ireg/app/php/returnAllCompounds.php", success: function(result){
formatted = jQuery.parseJSON( result );
vm.compounds = formatted;
}})
You could not get response of ajax call outside it success because they are asynchronous in nature. You need to use their call back to get that like success or you could also use .then function which get call when ajax call gets resolved.
NOTE
Don't mix jQuery ajax with AngularJS that will mess up with digest
cycle, you need to force it manually, Do replace ajax with $http
Update
Below is angular version $.ajax
$http.get("http://localhost:8080/ireg/app/php/returnAllCompounds.php")
.success(function(result){
formatted = jQuery.parseJSON( result );
console.log(formatted); //equals the correct object
}});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
This is probably a crazy stupid question, but I don't get why the things variable is not being reset. Here's what I have:
var things = "";
jQuery.get("/Users/MyName/Documents/File.txt", function(data) {
things = data;
});
console.log(things)
Whenever I do the console log within the function, it works. When I take it out of the function, it doesn't work. I thought I was setting the things var globally but apparently not?
var things = "";
jQuery.get("/Users/MyName/Documents/File.txt", function(data) {
things = data;
}).done(function() {
console.log(things);
});
is same as
var things = "";
jQuery.get("/Users/MyName/Documents/File.txt", function(data) {
things = data;
console.log(things);
});
Passing a function as second param into $.get, it will be called when AJAX request is succesfull(aka status = 200);
If you want to use it outside, your have to use done() method, and first param(a function) is called if successfull, second on error and third is always.
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
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Variable doesn't get returned from AJAX function
(2 answers)
JavaScript asynchronous return value / assignment with jQuery [duplicate]
(2 answers)
Closed 8 years ago.
I have the following method in JavaScript:
function getData(){
var result;
$.getJSON("app/data/ptl", function (data) {
if (data == null) {
return false;
}
var x_data = new Array();
var y_data = new Array();
$.each(data, function(index, value) {
x_data.push(index);
y_data.push(value);
});
result = [months_data,value_data];
});
alert('');
return result;
}
When this method is called, the exact data is retrieved. However when I remove alert('') the data is not received. Does anyone know a reasonable explanation for such problem?
That's because your function is asynchronous, and removing the alert makes the return r line being executed before the distant server answers.
You can't simply synchronously return from a function calling an asynchronous work. The usual solution is to provide a callback and execute what you want to do in the callback :
function fetchData(doWithData){
$.getJSON("app/data/ptl", function (data) {
if (data == null) {
return;
}
var x_data = new Array();
var y_data = new Array();
$.each(data, function(index, value) {
x_data.push(index);
y_data.push(value);
});
r = [months_data,value_data];
doWithData(r);
});
}
fetchData(function(result) {
// use result here
});
Your alert() and the return r; are OUTSIDE of the 'success' handler of your ajax call. Remember the AJAX calls are asynchronous. The alert forces the browser to wait for you to acknowledge the alert, which allows (usually) the AJAX call to complete and populate your r vairable. Without the alert, the .getJSON() returns immediately, BEFORE r is populated.
The $.getJSON() call sets up an asynchronous process. The function itself returns immediately (almost), but the callback function you pass in will be executed later, when the browser has actually received a response from the server you're contacting. Thus, it inherently makes no sense to return a value from such a callback, as nothing can or will pay attention to it.
Instead, you should do any work that requires access to the retrieved information inside the callback function.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript asynchronous return value / assignment with jQuery
I have the following javascript code, the time.php file has minute and hour output using json_encode function. If I move console.log inside the getJSON function it finds the correct values, however when I move it outside the function it shows as undefined.
var my_hour;
$.getJSON('../scripts/time.php', function(data) {
my_hour = data.hour;
});
console.log(my_hour);
The "$.getJSON" call is asynchronous; the interaction with the server takes time but the browser does not wait for it to finish. Thus, your code after the function call runs immediately, a long time before the callback runs.
it's because it's asynchronous. Ajax request made by $.getJson async call your script and variables my_hour is initialized after your console.log(my_hour).
If you want it to work that way, then you should put console.log in some setInterval.
http://www.w3schools.com/jsref/met_win_setinterval.asp
var interval = setInterval(function(){
if (my_hour != undefined){
console.log(my_hour);
clearInterval(interval);
}
}, 200);
But it's it's not a good practice anyway.., your code should be placed in callback function as mentioned above.
var my_hour;
$.getJSON('../scripts/time.php', function(data) {
my_hour = data.hour;
console.log(my_hour);
});