Unable to store value in global variable JS [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
I have a following piece of javaScript code:
var ws_path = "x";
$.get('ws.config', function(data) {
ws_path = data;
alert(ws_path); //alert 1
},
'text');
alert(ws_path); // alert 2
// output = alert 1 = value of data
// alert 2 = x
I have a confusion' why it is behaving like this?

It is because alert(ws_path); gets executed before the content is get from server for ws.config file. You need to write the code in success function of get to ensure that variable is modified after get request.
jQuery.get

The second alert is fired before the $.get request is completed.

The important point here is:
$.get('ws.config' ....
is a kind of ajax call and it takes some time to get the actual value from the server, and that anonymous function there is a callback function which gets called when the ajax call receives the response.
Here in your code if you want to have a ordered scenario you can do this:
var ws_path = "x";
$.get('ws.config', function(data) {
ws_path = data;
alert(ws_path);
continueScenario();
}, 'text');
function continueScenario(){
alert(ws_path);
}

Related

Javascript not returning request [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
function getCatFact() {
var catFact = "";
request('http://catfacts-api.appspot.com/api/facts', function (error, resp, body) {
var jsonObj = JSON.parse(body);
catFact += jsonObj.facts[0];
})
console.log("HERE IT IS: "+catFact);
return "Here is your CatFact" + catFact;
}
Seems very simple but I am doing something wrong. All this function returns is Here is your CatFact.. I tried putting the return inside the request function as well, with no luck. Would love any help.
The request is asynchronous. That means that the request will fire, and JavaScript will immediately move on the the next line before the response has made it back to the client. In your case, the stuff that prints the cat fact.
Returning the cat fact itself will not work in this instance, because you will return it before the response has returned and changed the empty string. You either need to call a function within the success callback or return the request object itself.

javascript function not returning a value but will write to console.log [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
This the data im getting from post is a simple object and the return value is always empty. Its logging to the console fine. any ideas?
function getTaskData(item){
var returnText = '';
$.post("index.php", {name: "getTaskData", pk: item.taskDataId}, function(data){
console.log(data);///Object {taskData: "Also - whats up with this?"}
console.log(data.taskData);///Also - whats up with this?
returnText = data.taskData;
},"json");
return returnText;
}
The code included in the block function(data) { ... is called a callback. It will be aynchronously called when the server's ajax call has finished. Whereas the return returnText will be called immediately.
Whatever you are going to do with the returntext (update DOM etc) will need to be done in the callback function

How to get the data from Jquery.get to a variable in Javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I want to load a data that I got from Jquery.get into the variable in another function. The way I have tried is
function setPolicy(){
jQuery.get('/webapp/myProject/getPolicy', function(policy) {
console.log(policy + " Policy"); //Just for Observation
}); }
and I want to load the data which is now stored in the Parameter Name "policy" into another variable in another function like the following
function loadAPI() {
var policy = setPolicy();
console.log("The policy is " + policy);
The result Shows in the console is just
The policy is
which mean the variable policy is not receive the data from the function.
What I would like to ask is How can I load the data from function "setPolicy" into the variable Name "policy" in another function calls "loadAPI" as a string? Thank you in advance.
You need to return the fetched value. Try to add this stmt in your code -
$.get('URL', function(data) {
$('.result').html(data);
return data;
});

Jquery return value from $.post() in 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've got a Javascript function called getCartProducts() which gets a JSON array via AJAX using $.post() which returns a value. I want to let my function return that value, but I don't know how to do that.
Here's my function:
function getCartProduct(id){
$.post('core/ajax/getCartProduct.ajax.php', {id: parseInt(id)}, function(data){
var result = data;
});
return result;
}
I know that this wont work, because te variable result is only active in the $.post() function, but I don't know how to get it straight.
Add a callback function (AJAX is Asynchronous, so your return is being hit before there is any data to return):
function returnData(param) {
console.log(param);
}
Now add that callback function as a parameter to your AJAX function, and lets run it:
function getCartProduct(id, callback){
$.post('core/ajax/getCartProduct.ajax.php', {id: parseInt(id)}, function(data){
callback(data);
});
}
getCartProduct(id, returnData);

How do I get JSON data from Rest APi [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am creating an object in javascript:
var t = null;
$.getJSON('http://localhost:53227/Home/GetData', function (data) {
alert(data);
t = data;
});
alert(t);
When I alert data, I get an object back.
When I alert t, it's null.
Can you please guide, how to set "t" to the returned data?
This will work as expected - the issue is not that t is not set, it's that you're doing alert(t) before the getJSON callback is executed. Try doing alert(t) immediately after t = data;
In other words, here's your current order of operations:
Set t = null
Call server script
alert(t) --> t is still null!
(some amount of time later) receive JSON response
alert data
set t = data
...as you can see, at step 3 't' will still be null. Try this instead:
var t = null;
$.getJSON('http://localhost:53227/Home/GetData', function (data) {
alert(data);
t = data;
alert(t);
});
Cheers

Categories

Resources