I know it’s been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question
The getJSON structure is as follows (found on http://api.jqueri.com):
$(selector).getJSON(url,data,success(data,status,xhr))
most people implement that using
$.getJSON(url, datatosend, function(data){
//do something with the data
});
where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?"
and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.
You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : «success», «notmodified», «error», «timeout», or «parsererror», and the xhr variable contains the returned XMLHttpRequest object
(found on w3schools)
$.getJSON(url, datatosend, function(data, status, xhr){
if (status == "success"){
//do something with the data
}else if (status == "timeout"){
alert("Something is wrong with the connection");
}else if (status == "error" || status == "parsererror" ){
alert("An error occured");
}else{
alert("datatosend did not change");
}
});
This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.
Hope this helps someone still looking for an answer to this question.
How do I handle 500 errors when using jQuery’s getJSON?
There have been a couple of questions about error handling with getJSON()
and JSONP, but I’m not working with JSONP, just ordinary JSON.
Another answer suggests using .ajaxSetup()
before calling getJSON()
, so I tried this:
$.ajaxSetup({
"error":function() {
alert('Error!');
}});
$.getJSON('/book_results/', function(data) { # etc
But I find that the alert always triggers, even when the result is well-formed.
Any ideas?
asked Mar 22, 2011 at 9:12
4
The getJSON
method does not natively return errors but you could dive into the xhr object that is returned as a parameter in the callback.
The getJSON
method is a shorthand function for jQuery.ajax
. Using jQuery.ajax
you can easily achieve error handling:
$.ajax({
url: 'http://127.0.0.1/path/application.json',
dataType: 'json',
success: function( data ) {
alert( "SUCCESS: " + data );
},
error: function( data ) {
alert( "ERROR: " + data );
}
});
answered Mar 22, 2011 at 9:32
halfpastfour.amhalfpastfour.am
5,7343 gold badges44 silver badges61 bronze badges
If you are using the jquery version 1.5 or higher you can use the new methods .success(function), .error(function) and .complete(function)
Example from http://api.jquery.com/jQuery.get/
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get("example.php", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
Works perfect for me. I hope this helps
answered Sep 13, 2012 at 18:33
Bibek ShresthaBibek Shrestha
32.5k7 gold badges31 silver badges34 bronze badges
you can see it on jquery api getJSON: http://api.jquery.com/jQuery.getJSON/
$.getJSON(url).done(function(data){
$("#content").append(data.info);
})
.fail(function(jqxhr){
alert(jqxhr.responseText);
});
//jquery1.5+
the fail callback will trigger when text is not the correct json string or any other fail solutions
answered Jul 31, 2013 at 1:55
leelee
1511 silver badge6 bronze badges
Using jQuery 3.2.1:
$.getJSON('/api/feed/update', function (data) {
console.log(data);
}).catch(function (jqXHR, textStatus, errorThrown) {
console.error(jqXHR);
console.error(textStatus);
console.error(errorThrown);
});
answered Sep 8, 2017 at 8:16
Please do the following. Pseduo code:
$.getJSON('/path/to_your_url.do?dispatch=toggle&' + new Date().getTime(), function(data, status, xhr){
if( xhr.status == 200 )
// all good and do your processing with 'data' parameter( your response)
else {
//error - check out the values for only in chrome for 'console'
console.log(xhr.status);
console.log(xhr.response);
console.log(xhr.responseText)
console.log(xhr.statusText);
}
}
Tim Cooper
157k38 gold badges329 silver badges279 bronze badges
answered Mar 8, 2012 at 21:35
0
TypeError: $.getJSON is not a function in jQuery, a common error you often get when working with jQuery functions. Our explanations below will help you solve this kind of error with causes and solutions.
In fact, getJSON() is a method which is included in many jQuery libraries. This method helps you load the JSON-encoded data from the server via a HTTP GET request. The TypeError: $.getJSON is raised implies that this method getJSON() is not found in the jQuery version that you have imported, it might be due to you have used the old versions or jQuery slim versions in the HTML file. For instance:
<html> <body> <h1>LearnShareIT</h1> <script src ="https://code.jquery.com/jquery-3.3.1.slim.min.js"> // Import the slim version </script> <script type ="text/javascript"> $.getJSON('https://learnshareit.com/api') </script> </body> </html>
Result:
Have you acknowledged the cause of the error? It’s because of the version of jQuery you have used, which in the above example is: 3.3.1.slim.min.js. It is a jQuery slim version so it does not include the getJSON method or many ajax functions.
To solve the error, we recommend you use a slim version or a full one or use a newer version of jQuery. Follow the next section to see how to solve this problem.
How to fix this error?
Use the jQuery full version
You should remember that this function getJSON() only works if you are using a full version or min version of jQuery but not the slim one. As the slim one excluded this function and some unused ones. Therefore you should use the full jQuery version, for example:
<html> <body> <h1>LearnShareIT</h1> <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"> // Import the full version </script> <script type="text/javascript"> $.getJSON('https://randomuser.me/api/', console.log) </script> </body> </html>
Output:
Use the jQuery min version
In the previous explanations, the getJSON() method may not present in jQuery slim versions which you imported. However, it is included in min jQuery versions and also the full jQuery version (as previous). That is the reason why you can use the jQuery min version too:
<html> <body> <h1>LearnShareIT</h1> <script src ="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"> // Import the min version </script> <script type ="text/javascript"> $.getJSON('https://randomuser.me/api/', console.log) </script> </body> </html>
Output
As can be seen, we have imported the jQuery min version as in the above example. To be honest, although there are many versions that include this getJSON function, we suggest you use the newest version instead because it can help you prevent some other errors while using it. Therefore, if you make changes to the version you used, the results can become different from what expected.
Summary
We discussed many ways to fix the TypeError: $.getJSON is not a function in jQuery. We suggest you import only one version of jQuery in your code and make sure it is the newest slim or full version, you can easily solve this problem with our tutorials.
Maybe you are interested:
- How To Solve TypeError: $(…).datepicker Is Not A Function In jQuery?
- Solution To TypeError: $(…).DataTable Is Not A Function Error In JQuery
- TypeError: $(…).animate is not a function in jQuery
I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.
Name of the university: HCMUT
Major: CS
Programming Languages: Python, C, C++, Javascript, Java, HTML, CSS, R
jQuery.getJSON( url [, data ] [, success ] )Returns: jqXHR
Description: Load JSON-encoded data from the server using a GET HTTP request.
-
version added: 1.0jQuery.getJSON( url [, data ] [, success ] )
-
url
A string containing the URL to which the request is sent.
-
data
A plain object or string that is sent to the server with the request.
-
success
A callback function that is executed if the request succeeds.
-
This is a shorthand Ajax function, which is equivalent to:
Data that is sent to the server is appended to the URL as a query string. If the value of the data
parameter is a plain object, it is converted to a string and url-encoded before it is appended to the URL.
Most implementations will specify a success handler:
1 2 3 4 5 6 7 8 9 10 11 |
|
This example, of course, relies on the structure of the JSON file:
1 2 3 4 5 |
|
Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.
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.
As of jQuery 1.5, the success
callback function receives a «jqXHR» object (in jQuery 1.4, it received the XMLHttpRequest
object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR
and textStatus
parameters passed to the success callback are undefined.
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript’s object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see https://json.org/.
JSONP
If the URL includes the string «callback=?» (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp
data type in $.ajax()
for more details.
The jqXHR Object
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 $.getJSON()
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; added in jQuery 1.6) 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.
The Promise interface in jQuery 1.5 also allows jQuery’s Ajax methods, including $.getJSON()
, to chain multiple .done()
, .always()
, and .fail()
callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Deprecation Notice
The jqXHR.success()
, jqXHR.error()
, and jqXHR.complete()
callback methods are removed as of jQuery 3.0. You can use jqXHR.done()
, jqXHR.fail()
, and jqXHR.always()
instead.
Additional Notes:
- Due to browser security restrictions, most «Ajax» requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
- Script and JSONP requests are not subject to the same origin policy restrictions.
Examples:
Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
Demo:
Load the JSON data from test.js and access a name from the returned JSON data.
1 2 3 |
|
Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.
If an error occurs, log an error message instead.
1 2 3 4 5 6 7 8 |
|
I’ve tried to parse the following json response with both the JQuery getJSON and ajax:
[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}]
I’ve also tried it escaping the «/» characters like this:
[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview </h1><h1>January 29, 2009</h1>"}]
When I use the getJSON it dose not execute the callback. So, I tried it with JQuery ajax as follows:
$.ajax({
url: jURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(data){
wId = data.iId;
$("#txtHeading").val(data.heading);
$("#txtBody").val(data.body);
$("#add").slideUp("slow");
$("#edit").slideDown("slow");
},//success
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest="+XMLHttpRequest.responseText+"ntextStatus="+textStatus+"nerrorThrown="+errorThrown);
}
});
The ajax hits the error ans alerts the following:
XMLHttpRequest=[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview </h1><h1>January 29, 2009</h1>"}]
textStatus=parseerror
errorThrown=undefined
Then I tried a simple JQuery get call to return the JSON using the following code:
$.get(jURL,function(data){
var json = eval("("+data+");");
wId = json.iId;
$("#txtHeading").val(json.heading);
$("#txtBody").val(json.body);
$("#add").slideUp("slow");
$("#edit").slideDown("slow");
})
The .get returns the JSON, but the eval comes up with errors no matter how I’ve modified the JSON (content-type header, other variations of the format, etc.)
What I’ve come up with is that there seem to be an issue returning the HTML in the JSON and getting it parsed. However, I have hope that I may have missed something that would allow me to get this data via JSON. Does anyone have any ideas?