jQuery Wait until data fetched [duplicate] - javascript

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

Related

How to get responseText from JavaScript Variable? [duplicate]

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

Javascript / jQuery from async: false to async: true and still get data from outside [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have a few functions that grab data using ajax and I can then get the result data from outside the function when needed.
Here is one example:
function myfunction() {
jQuery.ajax({
url: someurl
method: 'GET',
async: false,
success: function(result) {
myresult = result;
}
});
return myresult;
};
And this from outside I get the data like this:
myvar = myfunction();
Doing it this way I am able to get the data outside the function.
I have searched google and stackoverflow and I still can't understand it so I thought adding a function that I'm already using might help me understand better how to do this.
How can I convert this code so that when I set async to true I'm able to get the data from outside the function?
How can I convert this code so that when I set async to true I'm able to get the data from outside the function?
Simple answer, don't. You're approaching the problem in the wrong way.
Instead of trying to get data available outside the function, you could provide a callback function which the data should be passed to:
function myfunction(callback) {
$.ajax({
url: someurl
method: 'GET',
success: callback
});
};
myfunction(function(data) {
// work with the data retrieved from the async request here...
console.log(data);
});
Note: this pattern is a little redundant in this example as you could just give the anonymous function directly to the success property. In a real scenario you'd probably want to execute some actual generic logic in the success handler before calling the provided callback function.
Alternatively you could return the deferred object from the jQuery AJAX request and then use a done() handler to be executed when the object is resolved:
function myfunction() {
return $.ajax({
url: someurl
method: 'GET'
});
};
myfunction().done(function(data) {
// work with the data retrieved from the async request here...
console.log(data);
});
In either case the logic to follow is that the data from the request should be provided to the required function instead of being made globally available.

How to use javascript variable out of the scope? [duplicate]

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

JQuery GET assigning data [duplicate]

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.

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

Categories

Resources