Callback function being skipped on jQueries .getJSON command - javascript

I have the following snippet of code:
$('input#teamName').live('blur', function() {
var value = $(this).val();
if (value) {
$.getJSON('api/event_company/'+value, function(data) {
console.log('why does this not want to work?');
});
}
});
Basically all it's doing is requesting some data from the server when a form field changes. My problem is that nothing in the callback function every gets called even though I can see using firebug that it has successfully sent a request to the server and received a valid JSON response.
If I change the getJSON parameters to:
$.getJSON('api/event_company/'+value, alert('Blah'));
Then the alert pops up as expected. Any ideas what might be causing this behavior?

If the JSON is invalid, the parsing will fail and the handler won't be called. From getJSON docs:
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 http://json.org/.
See if your JSON validates.
Your second example is not correct. It should instead be,
$.getJSON('api/event_company/'+value, function() {
alert('Blah');
});

Related

Uncaught SyntaxError: Unexpected token o

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.

$.getjson not working / json storage

I'm trying to do a getJSON call to a page within my domain that is simply a json array, which is not returning anything given the script in my webpage:
<script>
$('#genButton').click(function() {
console.log("click");
$.getJSON("http://mygithub.github.io/repository/quotedb.json", function(data){
console.log("executing");
var entry = data[Math.floor(Math.random()*data.length)];
console.log(entry);
$("#quoteDisplay").text(entry);
}).fail(function() {
console.log( "error" );
});
})
</script>
When the button is clicked, the console logs the "click", but never logs "executing", but also doesn't log any errors related to the getJSON. The debugger also never pauses within the getJSON function.
My question is, 1. Is it valid for quotedb.json to be literally a webpage with just a single json array? Or does the page need to be annotated in some way so that the getJSON request knows where to pick up the json from? 2. If (1) is fine, then are there any other reasons you can see why nothing from the getJSON return function would appear?
The json is again one array of json objects, in the form:
{
"character": ""
"quote": ""
}
EDITS
With the edited code, it now outputs "click" followed by "error" from the .fail() method of the $.getJSON call now.
I tried removing the ?callback? section of the url as suggested below, which did not work.
The /repository/ section of my url seems to be necessary to access the file.
Try without ?callback=? at end of url, see jQuery.getJSON()
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.

js working in console but not from function

I'm calling the below function after the data from an ajax call is returned. It performs the first console.log() which contains the data from the ajax call. But the each() loop iterating through - response, does not console.log anything.
primaSaveOrder.prototype = {
start: function(response){
console.log(response)
$j('#primaId').val('');
$j('#dialog').closest('.ui-dialog-content').dialog('close');
$j.each(response['billing'], function(i, val) {
console.log(response['billing'][i])
});
},
}
I don't think my code is too wrong though because if I manually create a variable in the console equal to the output of - console.log(response) and then run the -
$j.each(response['billing'], function(i, val) {
console.log(response['billing'][i])
});
it works. What I would prefer to run is $j('#' + i).val(response['billing'][i]) instead of console.log(response['billing'][i].
This also works if I do it directly in the browser but not in the file. I assume it's related but I can't figure out how to fix it.
this is an example of what i am iterating with some data changed for privacy
{"billing":{"order-billing_address_firstname":"test","order-billing_address_lastname":"test","order-billing_address_street0":"6 test","order-billing_address_street1":"test","order-billing_address_city":"","order-billing_address_country_id":"GB","order-billing_address_region":"","order-billing_address_postcode":"16","order-billing_address_telephone":"","order-billing_address_vat_id":"","order-billing_address_prima_address_code":"0"},"shipping":{"order-shipping_address_firstname":"test","order-shipping_address_lastname":"test","order-shipping_address_street0":"6 test","order-shipping_address_street1":"test","order-shipping_address_city":"","order-shipping_address_country_id":"GB","order-shipping_address_region":"","order-shipping_address_postcode":"16","order-shipping_address_telephone":"","order-shipping_address_vat_id":"","order-shipping_address_prima_address_code":"0"}}
May be the type of response is String. In that case convert the response into json using
response = JSON.parse(response);
before using response for iteration.
I don't say, it will help, but there are several things that should be checked for issue root:
Check whether the elements exist and they are really unique (since ids are used). console.log(i, $j('#' + i).size()) may do the trick. I believe that there may be no elements to set values.
Use val argument directly instead of referencing it through response['billing'][i]. Though I don't see how the response var may be overridden or hidden, but let's use the value directly since it's passed into callback.

Why does this JSON.parse return error: "unexpected token illegal"?

I'm using an AJAX request. This is the first time I'm using JSON or any of it's methods. The ajax utility returns an argument to the onreadystatechange callback as the responseText or responseXML of the file I'm requesting. Using a simple info.txt and request.responseText will work fine but when I try info.js and JSON.parse it returns "Unexpected token ILLEGAL" when I've checked multiple times that my syntax is correct. Here is the JSON:
JSON:
{
first: 1,
second: 2
}
JSON.parse() is very strict in grammar. The key/value pairs should have the form:
string:value
So the "first" and "second" should be string in a JSON object.
Change your JSON to following code and it should be right
{
"first": 1,
"second": 2
}
You seem to already be using jQuery in your success callback. jQuery also has methods to perform AJAX requests such as $.ajax rendering your AJAX custom function pretty useless. In your case you seem to be requesting a javascript file (.js) which is different than JSON. So:
(function() {
$.getScript('json.js', function(result) {
// TODO: do something with the result
});
})();
or if it is JSON:
(function() {
$.getJSON('json.js', function(result) {
// TODO: do something with the result
});
})();
This being said you could still continue to use your method but JSON.parse(e) will always fail if your json.js doesn't contain a valid JSON string. To verify that it contains a valid JSON string you could validate it on http://jsonlint.com

Jquery getJson not calling callback

I have the following javascript code:
$.get("categories/json_get_cities/" + stateId, function(result)
{
//code here
}, 'json'
);
And the PHP code which processes it basically outputs something like this:
function json_get_cities($stateId)
{
//code here
echo json_encode(array('cities'=>$cities));
}
In the firebug console I can see that the ajax request is being made as expected, a 200 OK response is received, and a proper-seeming JSON object containing the cities is returned. However for some reason, the callback function I'm passing on to jquery is not being called.
Even putting a debugger call in at the top of the function, i.e
$.get("categories/json_get_cities/" + stateId, function(result)
{
debugger;
//code here
}, 'json'
);
doesn't work. However if I remove the 3rd argument of 'json' the function is then called (but the response text is treated as plain text instead of being a JSON object).
Here's the JSON response returned by the server:
{"cities":[{"id":"1613","stateId":"5","name":"Acton"}]}
Any thoughts?
Did you confirm that this is valid JSON? In jQuery 1.4 the JSON parsing is done in a strict manner, any malformed JSON is rejected and a parsererror is thrown.
Try console.log(arguments) in the callback to debug.
Also, you state that 'json' is the fourth argument, but it should be the third (as in your example).
Make sure the json is valid using this...
JSON Validator
Another way to debug some of these ajax problems is to use the .ajax method, passing GET as the method type, rather than the .get method. This will allow you to specify an error callback function in addition to a success method.
Remember, JSON field names must be surrounded with quotes like the values when writing json in files for jquery to load. Ex:
In code:
{
name: "value"
}
In JSON file:
{
"name": "value"
}

Categories

Resources