How to get responseText from JavaScript Variable? [duplicate] - javascript

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

Related

jQuery Wait until data fetched [duplicate]

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

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.

Unable to store value in global variable JS [duplicate]

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

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