$.getjson not working / json storage - javascript

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.

Related

send a javascript request to another domain and get the response - not in jsonp

i am really banging my head here for more then a day, i am trying to send a request and get the response from another site. i'm doing it with jsonp (from the obvious reason). but the response is not a JavaScript function definition, so it keeps failing.
can anyone in this planet help me get the response the right way.
i attached the code i wrote, again: because the response is not in json it's not working. (try to run it yourself and you'll see).
any suggestions?
<script>
function test()
{
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: 'https://www.facebook.com/ajax/typeahead/first_degree.php?viewer=1000009843914&token=1-1&filter[0]=user&options[0]=pending_request&lazy=1&token=v7&stale_ok=1&__a=1&__user=1000009843914& viewer=1000009843914',
});
}
function jsonp_callback(data)
{
var val=JSON.stringify(data);
myString = val.slice( 11 );
$('#container').html(myString);
/*for (;;);*/
}
test();
</script>
The server must be programmed to include the JSONP callback within its script file. If it only knows to return JSON, it will have no effect when the dynamic script tag is inserted into the page since JSON can at most provide an object--but it won't go anywhere unless the same file calls the function. In this way, it is different from Ajax, since a dynamically inserted script tag can only interact with your own code if it knows to call one of your functions. Just as an example, it might return:
jsonp_callback({facebooKData:[...]});
You should investigate how the Facebook API supports JSONP (not just JSON) for whatever you are trying to do. Typically APIs will accept a "callback" variable to determine which callback function it should use (which jQuery handles for you).

Should be really simple Jquery jsonp

Why does this not work? anybody:
In my code I have:
$.getJSON("http://isp123.co.uk/cw/NorthWales/Test.txt?jsoncallback=?",
function(data){
//This never gets executed
alert('here');
});
The text file can be viewed here:
http://isp123.co.uk/cw/NorthWales/Test.txt
This is not a JSONP response:
({"name" : "hello world"});
If you had a proper JSONP response, then your code should work.
The question mark in the "callback=?" part of the URL is changed by jQuery before making the request, your JSONP server needs to be able to dynamically create the JSONP "function" in response to the unique jQuery request. If you can't dynamically create your JSONP, perhaps you could use YQL/Yahoo pipes to turn it into JSONP?
This pipe should do the trick, to see if it works, use this URL instead in your getJSON function: http://pipes.yahoo.com/pipes/pipe.run?u=http%3A%2F%2Fisp123.co.uk%2Fcw%2FNorthWales%2FTest.txt&_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&_callback=?
I just tried this and it worked:
$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?u=http%3A%2F%2Fisp123.co.uk%2Fcw%2FNorthWales%2FTest.txt&_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&_callback=?", function(data){
//This always gets executed!!!
alert('here');
});
I don't know if you know enough about JSONP but this is not JSONP
?({"name" : "hello world"});
It really should be something like this http://isp123.co.uk/cw/NorthWales/Test.txt?jsoncallback=foo
foo({"name" : "hello world"});
From the jQuery.getJson manual page:
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/.
Your JSON is invalid according to http://jsonlint.com/
Here Clearly mentioned
As of jQuery 1.5, setting the jsonp
option to false prevents jQuery from
adding the "?callback" string to the
URL or attempting to use "=?" for
transformation. In this case, you
should also explicitly set the
jsonpCallback setting
and read jsonpCallback section
jsonpCallback,
Specify the callback function name for
a JSONP request. This value will be
used instead of the random name
automatically generated by jQuery. It
is preferable to let jQuery generate a
unique name as it'll make it easier to
manage the requests and provide
callbacks and error handling. You may
want to specify the callback when you
want to enable better browser caching
of GET requests. As of jQuery 1.5, you
can also use a function for this
setting, in which case the value of
jsonpCallback is set to the return
value of that function
Probably worth using jQuery.ajax() - http://api.jquery.com/jQuery.ajax/
You can pass in the dataType as "jsonp" and then jQuery takes care of all the callback business, but more importantly you can specify a function to run when there's an error, which may help you:
$.ajax({
dataType: "jsonp",
success: function(d) {console.log(d);},
error: function() { console.log("error") } //do your debugging in here
//add other parameters such as URL, etc
});
The error function you define can be passed 3 variables, read up on it on the ajax() page on the jQuery docs (linked at the beginning of my post) to find out more about that and how to use them.
Your problem lies with how your server is outputting the information. In the link you've supplied, the assumption is that any name placed in the ?jsonpcallback should result in wrapping the JSONP code in a function with that same name. It, however, is not the case.
So the next option is this: use a static function name in your server file and wrap the code. (e.g. use foo(<jsonp>) and stick with it) Then, you have to explicitly tell jQuery that we are going to use a specific function name (leave jQuery with the assumption it's supplying (and thus receiving) that name back, when in-fact you're just supplying it server side and filling in the blanks).
Once you have your file setup, use something like the following:
$.ajax({
// setup the request
url: 'http://isp123.co.uk/cw/NorthWales/Test.txt',
crossDomain: true,
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'foo', // "supply" the jsonp function (pseudo-defined)
// function to call when completed
complete: function(data){
alert(data);
}
// just in case, catch the error
error: function(j,t,e){
alert('AJAX Error');
}
});
So now when jQuery makes the call and it thinks it's supplying the callback, it's really just getting the server-defined callback in return. So, for the above to work, your text file should look something like this:
foo({name:"Hello, World!"});
Also, if you can, change your header to application/javascript, though this is some-what optional.

Twitter API getJSON for Status ID Meta -- Response Empty!

There are some similar posts on SO about this topic but they are all dealing with search and I am trying to do something different. I have tried to apply some of the logic in answers to other questions here but w/o success. Essentially I just want users to be able to enter a status update ID into a text field, hit a button then display all meta data associated with that tweet. If I leave the callback=? part off of the URL string I get a response back but it's empty, which is obviously due to the security restrictions put in place by the Twitter API.
Here is what I am working with currently:
$.getJSON("http://www.twitter.com/statuses/show/73051651728084992.json?callback=?",
function(Data)
{
if(Data.length)
{
var Content = "";
$.each(Data, function(i, Row)
{
alert("We Have Data");
Content += Row;
});
$("#Result").append(Row);
}
else
alert("No Result for that ID!");
})
Which comes back w/ no data, yet the request does come back w/ a 200 HTTP response. Obviously I am missing something as far as the callback goes, I am just not sure what. Just as a crude proof of concept I was going to output all of the data to the Result div and pretty it up later. Obviously first things first I need to actually have some data to work with!
What am I missing?
Remove the ?callback=? from the url and try again. You are asking Twitter's api to wrap the response in a callback ? which would result in invalid JSON. Also, whenever in doubt, load the url manually in your browser to examine whether the response is correctly formatted.
Also, change to this, since $.getJSON() returns an Object, not a string:
if (Data) {
var Content = "";
..
}

Callback function being skipped on jQueries .getJSON command

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

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