This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am using $.get functionality to get json data from action method. But out of $.get() function JavaScript variable getting default value.
code look like:
var data = 0;
$(document).ready(function () {
var url = "/Controller/Action";
$.get(url, null, function (Data) {
data = JSON.stringify(Data);
console.log(data);
});
console.log(data);
});
Output display look like:
[{"Name":"Jatin","Address":"surat","colorScheme":"#1696d3"},{"Name":"Jatin","Address":"surat","colorScheme":"#1696d3"},{"Name":"Jatin","Address":"surat","colorScheme":"#1696d3"}]
And then
Display 0.
How may I use Data value out of scope?
Don't declare 'var' in front of data in the $.get call. This declares a new variable. Since data is already defined outside the function scope, simple change the value by doing "data = JSON.stringify(Data);"
var data = 0;
$(document).ready(function () {
var url = "/Controller/Action";
$.get(url, null, function (Data) {
data = JSON.stringify(Data);
console.log(data);
});
console.log(data);
});
Edit: After chatting to OP, he was trying to use the response data from $.get in a synchronous manner. For that, I suggested either moving the code that relies on the response data in an ajax success function or use jquerys $.when() function
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
Code:
<script>
$(document).ready(function(){
var filepath = 'csv/data.csv';
var data_string = $.get(filepath);
console.log(data_string);
});
</script>
When I use console.log(data_string) I got the following output on the console.
When I read that, I found that "responseText" has the values which I want. So I just need to get "responseText" to another variable.
I tried var data = data_string.responseText. But it not worked.
You should attach a callback function to $.get. From your console i see that is a jqXHR Object. $.get method has a success callback function that is executed if the request succeeds.
Attaching a callback function includes automatically json parsed.
var filepath = 'csv/data.csv';
$.get( filepath , function(response) {
console.log(response);
});
You need to provide callback function to get response from server like below:
var filepath = 'csv/data.csv';
$.get( filepath , function( data ) {
console.log(data);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a javascript function in my code which fetch data from a server using a ajax post request.
function fetchData(keyword)
{
$.post(
'http://example.com/apiv5/ajax/',
{
command: 'fetchxxx',
token: 'xxxyyyzzz',
data: keyword
},
function(data)
{
return data;
}
);
}
i need to concatenate the data into a variable like this, here i actually call the function.
var msg = '<p class="question">'+thisGuy.data('description')+'</p>'+fetchData(thisGuy.data('title'));
Note that here thisGuy = $(this);
Now the problem is , the fetchData() function take few seconds to fetch and load the data but in the meantime javascript skip this process and put a 'undefined' as if the returned value of this function.
Now how can i tell them to wait until it fetch the data and once it done then concatenate data in that variable? i have seen the wait() method but can not understand how to use it.
You should understand that for any async call you cannot return anything from function. Only thing you can do it is wait for the request to complete and access the response in the callback.
Since the jQuery.post method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method. Take a look at documentation here https://api.jquery.com/deferred.done/
Try something like this.
function showMsg () {
var thisGuy = $(this);
fetchData(thisGuy.data('title'))
.done(function (data) {
var msg = '<p class="question">'+thisGuy.data('description')+'</p>'+data);
//Now you can use the msg
});
}
function fetchData(keyword)
{
return $.post('http://example.com/apiv5/ajax/',
{
command: 'fetchxxx',
token: 'xxxyyyzzz',
data: keyword
});
}
Turn fetchData into a promise and resolve it in the callback of the Ajax query
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Sorry, but I am new to jQuery so this may seem like a dumb question.
I have a generic function that will call a $.get to retrieve some data from a URL and I then want to assign to a variable, not a control.
Here's my function, it has been simplified to clear out the "noise"...
function LoadFromURL(url) {
var response = "";
$("textarea#dump").val("url=" + url); // Shows the URL, no problem
$.get(url, "", function (data) {
response = data;
$("textarea#dump").val(response); // Shows the data, no problem
});
$("textarea#dump").val(response); // Shows NOTHING!
return (response);
}
The problem is that the response value quite happily assigns inside the callback function, but when it gets to the return (response) then the variable is empty.
The Shows NOTHING line is fired too soon to be useful. You must start from the callback function and go from there. You could call a method from the callback.
Call it like this:
var cb = function(data) {
$("textarea#dump").val(data);
}
LoadFromUrl("someUrl", cb);
or inline like this:
LoadFromUrl("someUrl", function(data) {
$("textarea#dump").val(data);
});
Change your method like this:
function LoadFromURL(url, cb) {
$("textarea#dump").val("url=" + url); // Shows the URL, no problem
$.get(url, "", function (data) {
cb(data); //<-- call the CallBack method
});
}
This is more the behavior of javascript than jQuery, callbacks are a way of life in js.
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);
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