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?
Related
Is there a way to use an event to call a function when the JSON.Parse() has parsed all the objects from a file?
JSON.parse is synchronous. it returns the object corresponding to the given JSON text.
More about it from mozilla
now a good way of doing JSON.parse is shown below (inside a try-catch)
try {
var data = JSON.parse(string);
//data is the object,
//convert to object is completed here. you can call a function here passing created object
}
catch (err) {
//mark this error ?
}
Now there are discussions, about why JSON.parse is not async, like the ONE HERE
EDIT: Since question was changed.
JSON.parse() is a synchronous method, meaning that once it's called it will execute fully, before code execution continues.
var obj= JSON.parse(jsonString);
obj.prop; // obj is already accessible.
JSON.parse, doesn't actually load any files. It's also synchronous, meaning that code execution resume, after it has finished it's function, which is to parse a valid JSON string, to a JavaScript object.
If you want to execute a callback after a file has loaded, you'd need to look into requests, and ajax to be more precise. Here's a simple example using jQuery.
$.ajax({
url: 'url/to/file.json',
dataType: 'json'
}).done(yourCallback);
Just getting a simple .json file and parsing it, or not. Both fail anyway. I tried the solutions from other threads and none worked. console.log() shows an object, but I cant use it. I tried changing the json a few different ways but that didnt work. This is the .json file:
[ {
"name": "Alabama",
"abbreviation": "AL"
},
{
"name": "Alaska",
"abbreviation": "AK"
},
{
"name": "American Samoa",
"abbreviation": "AS"
},
{
"name": "Arizona",
"abbreviation": "AZ"
}]
It looks ok to me. So I added this function to use it:
function fillStates(){
var obj = $.get('states.json');
console.log(obj);
var states = JSON.parse(obj);
//console.log(states);
}
I guess you are misunderstanding jQuery $.get() method. It will return a Promise object and not the data you want:
As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.
That's why you are giving a [object Object] to JSON.parse() function.
You must use a success callback:
function fillStates(){
var obj = $.get('states.json', function(data) {
// It will be executed in case of sucess
console.log(data);
});
}
Usage of $.get is not correct since it is an async execution. This should work:
$.get( "states.json", function( obj ) {
var states = JSON.parse(obj);
});
Let's backup and examine what $.get() is. This method is simply a shorthand method for:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
See the reference documentation. Now let's jump over to the $.ajax documentation to understand how jQuery parses the return value:
Per the documentation:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, =[TIMESTAMP], to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
"json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true.
"text": A plain text string.
multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
So to sum things up, jQuery will interpret the response using it's intelligent guess method since you didn't specify a return data type. The data type will be inferred as JSON and will be parsed to a JavaScript object. For this reason, you shouldn't ever need to do JSON.parse(...) on the returned data when using a jQuery based ajax method such as $.get, $.post, $.ajax, $.load (the data method, not the event handling suite method) or $.getJSON.
Continuing on, AJAX stands for asynchronous JavaScript and XML. The asynchronous part is key here. The request is operated out of band while JavaScript execution continues on the page starting at the next line. In your case obj will be a $.promise, not the result. Parsing this using JSON.parse will result in an error.
You have two options from here:
Wait for the promise to resolve and execute on it using .done().
Pass a success callback function to execute upon successful completion of the ajax request.
Both examples are outliend below:
Using .done():
var obj;
function fillStates() {
$.get('states.json').done(function (data) {
obj = data;
console.log(obj);
});
}
Using a success callback:
var obj;
function fillStates() {
$.get('states.json', function (data) {
obj = data;
console.log(obj);
});
}
Before JSON.parse(), just check typeOf obj==='object'. If true then there is no need to parse as variable is already an object.
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>
I'm trying use jQuery's AJAX handling .load while passing several variables along with the request.
Normally, as a xmlhttp request GET, I would pass variables like so:
xmlhttp.open("GET","myfile.php?
var1="+data1+"&var2="+data2+"&var3="+data3+"&var4="+data4,true);
Using load, I can't get this to work (the request doesn't succed):
$('#txtHint').load("myfile.php?var1="+data1+"&var2="+data2+"&var3="+data3+"&var4="+data4 , null, function (){ });
In the space where it says "null" in the .load example, is the parameter for:
"data: This optional parameter represents a map of data that is sent with the request".
If I'm unserstanding that correctly, I believe I can use it to send my variables along with the request. However, I can't find information on how to format it.
How can I pass my variables along with the request using .load?
It looks like your method should work as a GET to myfile.php.
If you want to use the data parameter instead, then look at the official jQuery API docs for the .load() method (not to be confused with the .load() event handling method), where it says:
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
So you can pass it as a string or as an object.
As a string (which you more or less already have):
$('#txtHint').load('myfile.php',
"var1="+data1+"&var2="+data2+"&var3="+data3+"&var4="+data4,
function() { }
);
As an object (note that this makes your request a POST):
$('#txtHint').load('myfile.php',
{
var1: data1,
var2: data2,
var3: data3,
var4: data4
},
function() { }
);
Most of the examples in the jQuery docs don't use the data parameter, but the last two examples at the very bottom of the page (as of typing this answer) shows some basic examples of using it in the object format.
I'm giving my first steps in jQuery AJAX and had some questions. Kindly take a look at this code (which is part of a tutorial):
$.ajax("confirmation.html", {
success: function(response) {
$(".ticket").html(response).slideDown();
}
};
I'm aware ajax() is a jQuery method. I know it takes a url and settings as its two parameters. I also understand what success does and what are its three expected parameters. Overall I understand what this code does: it gets that html and places it into the .ticket class. What I don't understand is:
1) What is that response argument inside of the success function? I'm assuming is the data returned by the server as explained in the official jQuery documentation. If that's correct then I guess any kind of name would have served this purpose, "response" being nothing but a placeholder. Hope I got that right.
And,
2) I hope this is correct: The HTML method will replace the content of the "ticket" class by the data, named as "(response)" in this case. So "response" here is again a reference to the placeholder argument passed to the success function.
success wants a callback function. You can pass it whatever function you want. jQuery will call it with 3 parameters when the AJAX call is done:
( PlainObject data, String textStatus, jqXHR jqXHR )
In JavaScript, all parameters are optional. You don't have to name any of them. It's just the de facto standard with AJAX callbacks to just name the response parameter and ignore the others.