global var in javascript issue [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'm newbie and have to following question:
i declared a global variable and alter the value within a function. But outside the value is still the old.
var allowDrag = 'false';
$.get('/cakeorga2/ajax/is_admin/', function (data) {
allowDrag = data;
console.log ('allowDrag in function : '+allowDrag);
});
console.log ('outside of the function : '+ allowDrag);
the console log was:
outside of the function : false
allowDrag in function : true
Any suggestions?

$.get is a shorthand method of $.ajax:
Perform an asynchronous HTTP (Ajax) request.
An ajax call is usually async so the main console.log will be fired before the $.get execution is completed (as you can see in the console order) and in that moment the allowDrag value is still false.

You were trapped. Global variables behave exactly as you expected. The reason it does not have the new value in your second console.log is a different one: By the time you execute the console.log, the ajax call issued with $.get has not been answered yet. If you need to use it like that you must make the call synchronous by using the async: false option.

Use deferred.then() to call the second console.log() only after the value has been updated (ajax GET has been successful)
$.get('/cakeorga2/ajax/is_admin/', function (data) {
allowDrag = data;
console.log ('allowDrag in function : '+allowDrag);
}).then( function(){
console.log ('outside of the function : '+ allowDrag);
}
);
http://api.jquery.com/deferred.then/

This happens because your ajax call is asynchronous. Asynchronous (in your use case) means your outside of the function console.log will execute before your ajax call returns.

Do it synchronous with $.ajax()
var allowDrag = 'false';
allowDrag = $.ajax(
{
url:'/cakeorga2/ajax/is_admin/',
async:false
}).responseText;
console.log ('outside of the function : '+ allowDrag);

Well that might very well be because the console.log outside the function gets called before the one inside the function since you have to call the function yourself and the code around it gets "played" automatically. But since I'm not familiar with Ajax/jQuery I could be wrong.

Related

Scope in JavaScript / 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've clearly been writing too much CoffeeScript, as I am now realizing I do not have even a basic understanding of scope in pure JS.
After playing for a while, I cannot figure out the problem with the following--
$(document).ready(function() {
var myUrl = "http://notimportant.com/"
var photos = getPhotos(myUrl);
console.log(photos); //undefined
});
function getPhotos(url) {
var a;
$.get(url, function(data) {
a = data["photoset"]["photo"];
console.log(a); //my object
});
return a;
}
If I put a console.log(a) statement on the line right below 'var a = data["photoset"]["photo"];' it shows that it properly makes the GET request I'm looking for. But I'm finding it impossible to pass that object back to my main block of code, where I want to manipulate it.
Thanks in advance.
The reason photos is undefined is not because of scopes. Its because $.get is executed asynchronously. $.get() returns jqXHR object instead of an HTTP response.
onSuccess callback should be passed to getPhotos() in order to make it work correctly. Alternatively when().then() construct could be used.
$(document).ready(function() {
var myUrl = "http://example.com/";
getPhotos(myUrl, renderCatPhotos);
});
function getPhotos(url, onSuccess) {
$.get(url, onSuccess);
}
function renderCatPhotos(data) {
var a = data.photoset.photo;
console.log(a); // a is always available
}
note: you might not even need getPhotos function. You can simply $.get(url, onSuccess); in $(document).ready() instead.
Its not a matter of scope, its a matter of that you are returning an undefined variable before the $.get defines it. Consider making photos a global, then setting it in the $.get success function instead of setting it to 'a'. Inside the success function, you can then issue calls to other functions that would control displaying/processing the photos.

Return object list Jquery Ajax [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm calling a C# api through Jquery AJAX. I am able to loop through all of the data and print each in the console; however, I am not able return the data to a variable (var x) so that it contains all objects returned from the api call.
This is my code thus far:
var uri = 'api/products';
function test(){
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
var info = {};
$.each(data, function (key, item) {
// Add a list item for the product.
console.log(item);
info.append(item);
});
return info;
});
}
var x = test();
I have tried to just simply skipping the $.each() and returning data, with no luck.
Should I be using a method other than append? Or is there a way to just simply return data?
Thanks.
.done() is a promise (http://api.jquery.com/promise/), which takes a callback function. The callback function is void; nothing consumes its return...and the return in your code is the return for the (anonymous) callback function, not for test(), which is why you're seeing no value come out.
This is an asynchronous pattern. That means test() is going to return immediately, not waiting for the AJAX call to complete, and there's no value yet to put into x! The AJAX response will arrive later, at some unknown time. The purpose of the callback function is to allow you to (at that time!) do whatever it is you intend to do with the value you receive. You haven't shown us what that is in this example, but you're going to need to restructure it to happen after the promise is fulfilled.

Accessing a global variable inside of a function which is a parameter for another 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'm trying to access a global variable inside of the success function of a $.ajax() call. Basically I have something like this:
function someFunc(email) {
var ret;
$.ajax({
url: '/checkuseremail.php?email='+email,
cache: false,
success: function(data) {
if ( data != '1' ) {
alert(email+'\n'+data);
ret = false;
} else {
alert(email+'\n'+data);
ret = true;
}
}
});
alert(ret); // outputs "undefined"
return ret;
}
I'm aware that the alert() at the bottom is being called before the ajax response has been given, but I'm not sure what else to do. I would just put the return statement inside of the success function, but that would only return that function, not the parent one.
Any ideas how to do this?
Either take a look at $.Deferred() or pass in a callback function into someFunc as second parameter. Then call that callback function on success.
Given your last comment "... function is called as part of a form validation when form is submitted" I think that your requirement translates into a synchronous handling of the request.
In those cases, you can force synchronous behaviour on the ajax call.
Try adding:
async: false,
to your Ajax options.
Don't think of success like a function that returns a value. It's a setting of $.ajax() that determines what action to take on the success (event), like a controller.
There are a couple of issues.
You said it in your original post. You are calling the alert before control is back in the hands of the client.
The error message was telling you this. Undefined When you are returning a value from a function, you have to assign it to something. ret is global to our function but it's never assigned a value.
You also need to parse the data object returned for your value. I'm assuming the data != '1' is just some sample code? You are getting a JSON object back most likely, possibly XML but either way it's not properly parsed.
You should use $.get() instead of $.ajax(). $.get calls $.ajax and is the preferred method.
function someFunc(email) {
// assign the value returned to ret
var ret = $.get({ // 2 assign value, 4 use $.get
url: '/checkuseremail.php?email='+email,
cache: false,
success: function(data) {
if ( data ) {
anotherFunc(data); // 3 parse data in function
return false;//1 alert removed
} else {
return true;
}
}
});
alert(ret);
return ret;
};
`

$.getJSON() doesn't work correctly the first time the script runs, but it does the second time. How do I make it run the first time? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Here's my script which I type into Firebug:
var jsonData;
$.getJSON("./js/ohno.JSON",function(data){
jsonData = data;
});
console.log(jsonData);
Here's the .JSON file contents:
{"oh":"no"}
The first time I run the script in Firebug, it returns "undefined"
The second time I run it (without refreshing the page) it returns the Object.
If I refresh, the same thing happens -- first time running returns "undefined", and second time running it returns the Object.
The .JSON file is
How do I make it so that it returns the Object the first time I run the script?
getJSON is async; meaning that script execution will continue, while it still loads the data.
You have to wait until it finishes.
var jsonData;
$.getJSON("./js/ohno.JSON",function(data){
jsonData = data;
console.log(jsonData);
});
You need to place the console.log (and any other code you want to run on data) inside the callback function:
$.getJSON("./js/ohno.JSON",function(data){
jsonData = data;
console.log(jsonData);
});
You can also use .ajaxComplete if you feel the need to keep it separate.
getJSON is asynchronous, which is why you have to provide a callback to handle the data. The request is fired off, but it hasn't completed by the time you get to your console.log, so the value is undefined. It finishes a short time later and sets the variable.
Move your console.log handler into your callback, and all should work as expected.
The anonymous function is an asynchronous callback, so it gets called after your console.log.
Here is the right way to do it :
var jsonData;
$.getJSON("./js/ohno.JSON",function(data){
jsonData = data;
console.log(jsonData);
});
The getJSON function is asynchronous, so the success callback function only gets executed once the request finishes. Your console.dir() is initially executing before the response happens.
Put the console.dir() inside your getJson handler function.

$.getJSON to make its result global [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm using the jQuery function $.getJSON to get some data from the server side and here is the code:
function (){
$.getJSON("someURI",function(result){
//this alert works fine
alert(result.msg)
});
// this prints the data as undefined
alert(result.msg);
}
how to change the scope of "result" returned from $.getJSON in order to make it global.. to make the second alert prints its value not to be undefined ??
You can't. AJAX is asynchronous meaning that you can access the result variable only inside the success callback. You could make it global, but remember that the line immediately following the $.getJSON call will be called much before the success callback executes rendering it useless.
So no global variables, consume the results of an AJAX call inside the callback:
function () {
$.getJSON('someURI', function(result){
// only here you can hope to consume the results of an AJAX call
alert(result.msg)
});
}
That's how AJAX works. The A in AJAX stands for asynchronous.
This is an asynchronous call.. So you must wait till the server responds...
In your case, the outer alert will be undefined as the server hasn't responded yet...
Also, the scope of result is limited to callback function, it's inaccessible...
You can do it like this though:
var myJSON;
var serverResponded = 0;
function () {
$.getJSON("someURI", function (result) {
//this alert works fine
myJSON = result.msg;
serverResponded = 1;
});
setTimeout(function () {
if (serverResponded) {
alert(myJSON);
}
}, 500);
}
The $.getJSON call is a shortcut to an Ajax call, and “Ajax” stands for “Asynchronous JavaScript and XML”.
Let's suppose you add var globalResult and that you perform a globalResult = result; in your success function. So, when you do a call to globalResult outside the callback, globalResult won't be assigned yet. So, if you really have to process it outside, you can check if it's assigned with a function called setInterval, but this is going too far.
save it into another variable something like this
function (){
var something;
$.getJSON("someURI",function(result){
//this alert works fine
alert(result.msg)
something = result
});
if you want it to be scoped outside your function wrapper, do something like this
var something;
function (){
$.getJSON("someURI",function(result){
//this alert works fine
alert(result.msg)
something = result
});

Categories

Resources