How do you get responseText from jQuery.getJSON method in javascript? - javascript

I am trying to read in a JSON file from my directory using the jQuery.getJSON method and it returns the object shown in the picture. I want to get the responseText from the object but cannot figure out how.
var jsonData = jQuery.getJSON('relationalData.json');
Ive tried to use the following to extract the responseText but they all failed.
var response = jsonData.responseText;
var response = jsonData['responseText'];
I also tried using without any luck, as the method doesn't even get called with a json file. It worked when I used an xml though.
$.get(filename, function(data){
var responseText = data;
});

A similar solution to guest271314 but, maybe, still instructive for someone ...
$.getJSON('http://ws.spotify.com/search/1/artist.json?q=foo')
.done(function(obj,status,xhdr){$('#out').append(xhdr.responseText);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="out"><div>
The important part is to look for the .responseText property in the xhdr object, which can be accessed though the third parameter of the callback function.

Came across this question which has been longed asked, but for future visitors where is my solution:
$.getJSON method fetches data from a server using HTTP GET request, the response on successful call returns in a responseText property as you see in your console.
Therefore to get the data of the responseText you have to use the JSON.parse() method to retrieve data to javaSrcipt object like this:
var jsonData = JSON.parse(jsonCall.responseText);
But $.getJSON() method is asynchronous so this must be done inside the callback function if not the response may not exist.
Final solution:
var jsonCall = $.getJSON('URL',function(){
var jsonData = JSON.parse(jsonCall.responseText);
console.log(jsonData);
});

Try utilizing .then() , substituting responseJSON for responseText
var jsonData = jQuery.getJSON("https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/a5ac6cffdc1ffab39f9db425844721b528751654/a.json");
jsonData.then(function(data, textStatus, jqxhr) {
alert(jqxhr.responseJSON)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Related

Fetching local text file and assign contents to a variable

For as simple as this should be, I have no idea what I am doing wrong. I'm attempting to fetch a local text file and store it in a variable, but regardless of the method (fetch api, $.get and ajax) I use, I always get undefined.
$(document).ready(function() {
var fileConfiguration;
$.get( "Configuration.h", function( data ) {
fileConfiguration = data;
});
document.getElementById("demo").innerHTML = fileConfiguration;
});
The data variable is properly fetched, I can use alert or console.log and see the contents correctly. When I assigned it to a variable though, it's undefined. I imagine this has something to do with it being an asynchronous callback, but can't figure out the problem.
As you and #charlietfl have pointed out the AJAX request is asynchronous which means that the last statement in your code is executed before there's a response, hence fileConfiguration is still undefined.
Therefore the best place to do the assignment is inside the callback like so:
$(document).ready(function() {
$.get( "Configuration.h", function( data ) {
document.getElementById("demo").innerHTML = data;
});
});

Read & parse JSON response from API

I have an API endpoint like this:
https://client.systemonesoftware.com/bannink/json/?language=nl
I need to read and parse it into a table with all the information. But I get no output when I try to do it with Javascript.
<script>
$.getJSON('https://client.systemonesoftware.com/bannink/json/?language=nl', function(data) {
var json = JSON.parse(data);
alert(json.cached);
alert(json.data[1].id);
});
</script>
This piece of code gives nothing..
$.getJSON returns JavaScript object so you don't need to parse it, try:
$.getJSON('https://client.systemonesoftware.com/bannink/json/?language=nl', function(json) {
console.log(json.data[1].id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.
I believe your issue is that the data already comes through parsed:
<script>
$.getJSON('https://client.systemonesoftware.com/bannink/json/?language=nl', function(json) {
alert(json.cached);
alert(json.data[1].id);
});
</script>

Cannot Access responseJSON object

I have the following code and I want to access the json of the outside of the initial call.
var crimes = $.getJSON('url');
console.log(crimes);
the console logs an object with a "responseJSON" element, but I can't access it. The code:
console.log(crimes[responseJSON]);
returns an error saying respponseJSON is undefined. I need to cycle through this large dataset in another for look so I only want to call it once rather than every time in the loop that comes after. How do I access the responseJSON object?
$.getJSON returns a jqXHR object, and while it may have a responseJSON property, you cannot access it this way (or at that moment). You have to "wait" until the browser performed the Ajax request. You do this by passing a callback to $.getJSON, which gets called when the response is available.
From the jQuery documentation (adapted):
$.getJSON( "ajax/test.json", function( data ) {
// access data here
});
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.
It seems you are not familiar with Ajax, so you should definitely read the jQuery tutorial about Ajax.
See also: How do I return the response from an asynchronous call?

responseText Field Undefined [duplicate]

This question already has answers here:
jQuery: Return data after ajax call success [duplicate]
(5 answers)
Closed 8 years ago.
I am using jQuery to pull in data from a csv. The request is successful (Success!! in the console) and I can see the data in the responseText field when I print the object but I can't print data.responseText (shows in console as "undefined").
window.onload = function(){
console.log("start");
var data = $.ajax({url:"http://localhost/bootstrap/data/930.csv",success:function(){
console.log("Success!!");
}()
});
console.log(data);
console.log(data.responseText);
How do I access responseText to transform it?
EDIT:
Updated my code per comments to force sync and modified the variables to better follow them. Still I was surprised by the result.
console.log("start");
var ajaxData = $.ajax({url:"http://localhost/bootstrap/data/930.csv",async:false,success:function(dataReturned){
console.log("Success!!"); //Success!!
console.log(dataReturned); //Returns my csv data
console.log(dataReturned.responseText); //undefined
}
});
console.log(ajaxData); //Returns a jQuery object that included my csv data
console.log(ajaxData.status); // Returns 200
console.log(ajaxData.responseText); //Returns my data (same as dataReturned in success function)
So I guess I also missed that the jQuery object isn't created and available until the complete $.ajax call finishes but the response is available sooner.
Thanks for the help.
Please learn about asynchronous methods. You need to use the callback. What you tried to do is eat a delivery pizza right after you hung up the phone. You need to wait until the guy delivers it.
$.ajax({url:"http://localhost/bootstrap/data/930.csv",success:function(data, status, xhr){
console.log("Success!!");
console.log(data);
console.log(xhr.responseText);
}
});

Does jQuery support reading JSON from X-JSON HTTP headers?

Is jQuery able to read JSON data from X-JSON HTTP headers returned by the server? I've been searching through the jQuery docs, but all the examples I can find use JSON returned in the request body rather than the headers.
Yes, you need to call the getResponseHeader method of the XMLHttpRequest object, and do the JSON de-serialization manually:
function getHeaderJSON(xhr) {
var json;
try { json = xhr.getResponseHeader('X-Json') }
catch(e) {}
if (json) {
var data = eval('(' + json + ')'); // or JSON.parse or whatever you like
return data
}
}
Note that the try/catch is for some versions of Firefox where if the header is not present an error is thrown. I can't remember which version(s) were affected.
You have a couple ways to get a reference to the XMLHttpRequest object in jQuery:
hook into the complete callback of the ajax request, as opposed to the expected success callback (jQuery is kind of inconsistent wrt to what args are passed in what order to what callback function or global ajax trigger):
$.ajax({
// ...
complete: function(xhr) {
var data = getHeaderJSON(xhr);
// do with data as you wish
}
})
Alternatively you can save a reference to the XMLHttpRequest object returned to you from calls to .ajax/.get/.post etc, via a Closure. This allows you to use it inside whatever callback you choose (ie success or complete, or error for that matter):
var xhr = $.ajax({
// ...
success: function() {
var data = getHeaderJSON(xhr); // access xhr var via closure
// do with data as you wish
}
});
So to answer your title directly: no, jQUery obviously doesn't support this OOTB.
as of 1.4 jQuery's success: callback receives XMLHttpRequest -- (data,textStatus,XMLHttpRequest). So you don't have to use the complete: callback anymore, as laid out above.
Wish I could reply to the previous answer instead of adding a new answer.

Categories

Resources