I dont get any data from the getJSON function - javascript

I am trying to get a JSON object from a .jsp page. But I dont know what to do with it. I've googeled this for some time now, but I can't find out what this getJSON functions does.
Does it return a string representation of a JSON object?
Or is the parameter 'json' that is passed into the function the JSON Object?
Is the function (the second parameter) equivalent to the function that one write when using XMLHttpRequests? In other words; is this function the asynchronous part?
The alert with "JSON stuff" doesnt print.
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var jso = $.getJSON(URL, function(json) {
alert("JSON stuff " + json.name);
});
alert(jso);
//alert(jso.name);
}

A few things to check:
Is the webapp also running at localhost:8080? If not, you might be running afoul of the same origin policy, in which case you would need to encode to jsonp.
You should also check in firebug/inspect element/whatever to make sure you are actually getting something returned from your request. You can do this in the network or resources tab depending on which browser you are using. Also stick a breakpoint in your script before the alert and inspect the json object to see if anything was returned.
The second alert isn't firing because the json object doesn't exist yet when you call it.

The relevant docs for getJSON is here. The callback parameter (that you named json) is the already decoded data (i.e. it's a JavaScript object, not a string).
As for why your alert isn't doing anything, see Charles Bandes's answer. To better debug your code you can also use console.log (will work on Firebug or on Chrome), and/or set a handler to ajaxError - so if the problem is with your request you can be notified of the error (instead of the browser ignoring it by default).

Does it return a string representation of a JSON object?
The respone will come as JSON format. getJSON method is a short form of jQuery ajax with datatype as json . The datatype decides what is the format to receive the result from the ajax call.
is the parameter 'json' that is passed into the function the JSON
Object?
The variable json in your callback function will get the response from your ajax call. The data should in a valid JSON Document( if your server pages returns like that properly)
is this function the asynchronous part?
As i told you earlier, getJSON is a shortform of jquery ajax with datatype as Json. It is asynchronous.

Related

How to retrieve a json from JavaScript

I am trying to write a HTML5 mobile application and use jQuery to get a json from the url
http://cin.ufpe.br/~rvcam/favours.json I tried using
var url='http://cin.ufpe.br/~rvcam/favours.json';
$.getJSON(url, function(data, status)
{
console.log(data);
console.log(status);
});
but nothing shows up on the console. I don't see what I am doing wrong.
[EDIT] I learned from another post that I can't normally retrieve information from another server. But this server in particular (cin.ufpe.br/~rvcam) is mine. Can I use PHP or some other method to allow my application to retrieve the data?
The URL doesn't return valid json. It returns some JavaScript that attempts to execute a function called "foo" and passes the object as an argument. This is commonly called "jsonp". It is a method of achieving cross domain ajax calls
Your http://cin.ufpe.br/~rvcam/favours.json file isn't valid json. The valid json is wrapped in foo(). Remove the foo() from that file and it will work.

jQuery: Server Side Code and Erroreems

Here is a quite straight forward jQuery code I find on one site:
//It simply loads more news
function ReadMore(page){
$("#news-list").html('Loading More News...');
$("#news-list").append('<img src="/images/loading.gif">');
next=parseInt(page)+1;
html=$.get('/morenews.php','page='+page,function (data){
$("#News").append(data);
$("#news-list").html("<a href='javascript:void(0);' onclick='ReadMore("+next+");'>More News</a>");
});
}
My question is:
What kind of datatype is it using? "Expected data type of the response. One of: null, 'xml', 'script', or 'json'. "
What is html=$.get('/newread.php','page='+page,function (data){} in jQuery? I have never seen $.get and there seems to be one parameter page.
Does the server receive something like this: /morenews.php?page=3
This code cant deal with errors. If the server is too busy, let's say, doing nothing for 20 seconds, how can I add some error messages?
By the way, jQuery seems to be a weird language because it constantly create anonymous functions.
page is an integer (although it gets typecast to a string when sent to the server as part of an HTTP GET request). data is an html string.
See jQuery.get( url , data , success() ). It's shorthand for $.ajax(). The success() function is a callback, which gets exectuted once a response is received from the server.
Yes: /morenews.php?page=3
You could try adding a timeout function to cancel the request if there's been no response within a given time.
The language is Javascript (jQuery is just a library), and anonymous functions are really cool when you get used to them...
get() is used by jQuery to load data from a server using an HTTP get request. There's also a .post() method to use a post request, etc.
More info on .get() can be found here.....
http://api.jquery.com/jQuery.get/

JSON.parse works but jQuery.getJSON returns http error 403

When I use JSON.parse(jsonString), the JSON is parsed no problem at all.
var result = JSON.parse(jsonString);
But when I use jQuery.getJSON(jsonString) i received an http error 403.
var result = jQuery.getJSON(jsonString);
Any idea why one will work and the other will not? They are both reading a string.
Thanks!
They are both reading a string.
Oh no! Those two methods are so very much different. They have absolutely nothing in common. They are accomplishing 2 entirely different tasks.
The first simply parses a JSON string into a javascript object:
var result = JSON.parse('{"foo": "bar"}');
alert(result.foo);
will show bar. Also notice that the JSON.parse method is a built-in method in modern browsers. It's pure javascript and has strictly nothing to do with jQuery. Legacy browsers do not support it. For them you need to include the json2.js script to your page.
The second performs an AJAX call and expects as argument an url:
jQuery.getJSON('/someserversidescript', function(result) {
// callback to be executed when the AJAX request succeeds
});
As you can see here the argument is an url. Calling jQuery.getJSON('{"foo": "bar"}') makes strictly no sense. I guess that's the reason why your server responds with 403 error, since this is not valid url on your server. It expects that the server will return a JSON string as response. It's simply a shorthand for:
$.ajax({
url: '/someserversidescript',
type: 'GET',
dataType: 'json',
success: function(result) {
// callback to be executed when the AJAX request succeeds
}
});
getJSON() is an asynchronous call back to a server that returns a JSON object. JSON.parse() takes a string and returns a JSON object in memory. They are completely different.

jQuery: using $.getJSON to get localization from aprs.fi

I want to use JSON to get localization coordinates from http://aprs.fi/page/api. I found example at http://api.jquery.com/jQuery.getJSON :
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "cat",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});
</script>
When $.getJSON succed, it runs function(data), it puts 4 images on website. I paste this code in my html file and it works, so I changed it to get JSON data from aprs.fi:
<script>
$.getJSON("http://api.aprs.fi/api/get?name=OH7RDA&what=loc&apikey=_key_&format=json",
function(data)
{
alert("Anything");
});
};
</script>
Maybe my query is wrong, but even "Anything" doesn't print on my screen. I have no idea how to change it to make it works.
Just because a service can return JSON-formatted results does not mean that you can access it via JSONP. The site has to explicitly recognize such a request so that the response works as a JSONP response. (That is, the response must take the form of a function call, with the JSON return data passed as the argument to the function.)
The XHRs that getJSON is using are subject to same-origin-policy in web browsers; you can point XHR only to from only the exactly same server, port, protocol combination as the web page they are used in. If your web page runs on http://example.org:5625 it can only point XHR requests to http://example.org:5625/some-path-here.
The workaround is called JSONP where the resource is loaded as a tag. However, the service in question needs to be aware of it. You can tell if it is because after appending the callback parameter it should show something like
callbackname({"the": "respose", "goes": "here"});
that is, a function call to the named callback. However, if I understood correctly, the service you are using does not support JSONP. Then your only option is to make a serverside script that works as a proxy.

jQuery.ajax() + empty JSON object = parse error

I get a parse error when using jQuery to load some JSON data. Here's a snippet of my code:
jQuery.ajax({
dataType: "json",
success: function (json)
{
jQuery.each(json, function ()
{
alert(this["columnName"]);
});
}
});
I get no errors when parsing a non-empty JSON object. So my guess is that the problem is with my serializer.
Question is: how do I format an empty JSON object which jQuery won't consider malformed?
This is what I've tried so far, with no success:
{[]}
{[null]}
{}
{null}
{"rows": []}
{"rows": null}
{"rows": {}}
UPDATE:
I can understand that I've been somewhat vague--let me try and clarify:
Parsing of the JSON object is not the issue here--JQuery is - I think.
jQuery throws a parse-error (invokes the error function). It seems like jQuery's internal JSON validation is not accepting any of the before mentioned objects. Not even the valid ones.
Output of the error function is:
XMLHttpRequest: XMLHttpRequest readyState=4 status=200
textStatus: parsererror
errorThrown: undefined
This goes for all of the before mentioned objects.
The solution is to return a status code of 204 rather than 200 from the server, 204 is "no content" and it will return success while not trying to invoke the parser
Firstly {[]}, {[null]}, and {null} won't work because they are all invalid JSON objects (as verified by the JSON validator).
The remaining objects are all valid JSON objects, so your success function should be getting invoked.
If you pass a non-array or array-like object object then the each function will enumerate your json object by its named properties. In the case of your three objects that each have a rows property this will be set to [], null, and {} respectively, none of which have a columnName attribute so an undefined error will be thrown.
Your {} object on the other hand has no properties, so shouldn't be causing an error because the each call will loop 0 times. What does the following line display if you add it as the first line in your success function?
alert(typeof json + ' ' + (json == null));
you are looking for this:
[]
an empty array. That is, if you plan to iterate over it right away, then what you need is an array.
Your web service may be returning null. I've found that returning null from a web service call returns a response with status code 200, "Ok", but jQuery throws a parseerror afterwards.
If this is the case, it has nothing to do with what you're sending up to the server, and everything with what the server is sending back.
If you're able to change the web service, you might want to try returning an empty JSON object, or a default value instead of Null. Alternatively, you could check for this error scenario in your error handler, knowing that this means your call returned null.
Did you verify if the JSON is returned correctly in the first place before the each? Set the empty value as {}, and verify if it is like that before .each
Also it would help to know how your JSON looks like when there is data.
Instead of:
$(json).each(function () { ... });
I think you want to be using:
$.each(json, function () { ... });
From the jQuery.each documentation:
This function is not the same as
$().each() - which is used to iterate,
exclusively, over a jQuery object.
This function can be used to iterate
over anything.
I was experiencing similar problems when requesting valid JSON from the server.
My server was serving the content-type of text/javascript
I was not using the optional jQuery.ajax setting of 'dataType' so jQuery was interpretting the output a javascript (eg padded JSON), not neat JSON.
Adding a dataType:'JSON' to the settings object passed to jQuery's ajax method solved the problem.
Had this problem as well, and solved it by using the jsonserializer in my web service to format an empty string. result is was "\"\"" essentially "" ;

Categories