Scope and $.get [duplicate] - javascript

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.

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

Why don't I have access to a variable created in the upper scope [duplicate]

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

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

Javascript Scope: variable not defined [duplicate]

This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
In the following code the alert inside the function works fine, but the second has variable undefined, and yet I have delcared the variable outside of the function. Why is this?
var data = [];
$.post(
'matchEngine.php',
function(data) {
for (var i = 0, len= data.length;i <len; i++) {
for ( h = 0, len2= data[i].length;h <len2; h++) {
data[i][h][0]=(data[i][h][0])*30;
data[i][h][1]=(data[i][h][1])*30;
data[i][h][3]=data[i][h][3].replace(/\"/,"");
}
}
alert(data[0][0][0]);
}
);
alert(data[0][0][0]);
if you are suffering a similar problem the following How to return the response from an AJAX call? has the definitive explanation and answer.
The reference data in the function parameter and outside the function are different variables. In first case, it is in global scope, and in the second it in the local scope..They are completely different.
The example illustrates the issue....
var data=2;//this
function fun(data){ //and this are different
alert(data);
}
var data2=3;
fun(data2);
You can try this:
var data = [];
var myRequest = $.post(
/* your stuff */
);
myRequest.done(function() { alert(data[0][0][0]); })
As pinkpanther noted, the local data variable inside your $.post callback is not the same variable as the data variable outside the function.
Additionally, since $.post is asynchronous, you need to either pass it a callback or use the deferred object that it returns to access the response.
$.post('matchEngine.php').then(function(data){alert(data)})
for example, if you want to be able to pass the response around to other functions, you can do something like:
function doPost(url){
return $.post(url);
}
function processResponse(response) {
alert(response);
}
responsePromise = doPost("matchEngine.php");
responsePromise.then(processResponse);
As an aside, I recommend using $.ajax instead of $.post if you are going to use the callback style instead of promises. The reason being that $.ajax provides an error callback while $.post does not.

Categories