Parse Google Latitude JSON in Javascript (without PHP) - javascript

I'm no developer but am pretty good at copy/paste.
I'm trying to parse the Google Latitude JSON (https://latitude.google.com/latitude/apps/badge/api?user=xxxxxxxxxxxxxxxxx&type=json) in a webpage (JavaScript). Is that possible without PHP? and if so, could you show me some example code?
I've been looking but all the examples I found use PHP.
I used the following code:
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// script goes here
$.getJSON('https://latitude.google.com/latitude/apps/badge/api?&user=xxxxxxxxxxxxxxxxxxx', function(data) {
alert(data.type);
});
});
</script>
</body>
</html>
This code I have tried gave an error:
3 requests ❘ 21.38KB transferred ❘ 470ms (onload: 448ms, DOMContentLoaded: 448ms)
104ms157ms209ms261ms313ms366ms418ms470ms
OPTIONS https://latitude.google.com/latitude/apps/badge/api?&user=xxxxxxxxxxxxxxxx 405 (Method Not Allowed) jquery.min.js:19
o.extend.ajax jquery.min.js:19
o.extend.get jquery.min.js:19
o.extend.getJSON jquery.min.js:19
(anonymous function) json.html:12
o.extend.ready.o.readyList jquery.min.js:19
o.extend.each jquery.min.js:12
o.extend.ready jquery.min.js:19
(anonymous function) jquery.min.js:19
XMLHttpRequest cannot load https://latitude.google.com/latitude/apps/badge/api?&user=xxxxxxxxxxxxxxxxxxxxxx. Origin h ttp://dl.dropbox.com is not allowed by Access-Control-Allow-Origin.

In order to make a cross-domain AJAX request, you need to use either CORS or JSONP. This is something the server must support. It doesn't seem that Google Latitude supports this, so you need to use a server-side language (such as PHP) to get the data.
EDIT: If you don't want to use PHP, and you only want to use JavaScript, you can use Yahoo's YQL (you might need an API key).
var googleURL = 'https://latitude.google.com/latitude/apps/badge/api?user=xxxxxxxxxxxxxxxxx&type=json';
$.getJSON('http://query.yahooapis.com/v1/public/yql?callback=?', {
q: 'select * from json where url="'+googleURL+'"',
format: 'json'
}, function(data) {
if(data.query.count){
var gData = data.query.results.json;
alert(gData.type);
}
});

You don't need to parse the JSON, $.getJSON will do that for you, and give you back a JavaScript object. Your error is unrelated to the JSON itself - you're attempting to do a cross-site request which is being prevented by browser security policies. I'd suggest reading up on JSONP
http://json-p.org/
Cheers

Seems like you are using wrong url.
Remove "&" before "user", and add "type" parameter: https://latitude.google.com/latitude/apps/badge/api?user=xxxxxxxxxxxxxxxxxxx&type=json
Plese note that user id can start with "-" sign.
Also, seems like you tried to use dropbox as the hosting, thats prevent you to make ajax request. Try to load your html page from your local drive or from regular web server.

You have a Cross-site request.
See this last line of error: XMLHttpRequest cannot load https://latitude.google.com/latitude/apps/badge/api?&user=xxxxxxxxxxxxxxxxxxxxxx. Origin h ttp://dl.dropbox.com is not allowed by Access-Control-Allow-Origin?
Your original script is hosted at one server, say your server. It can only ask for data from that same domain. Even if you use different ports (http/https), it will not work.
You could possibly make it work with this.
Another possible solution would be to create a php script or similar on your server that will fetch the data from YAHOO and just dump the output in the result.
Then your jQuery ajax call would call your own script (on your server, hence no Cross-Site
HTTP request is happening) and it would work this way. Not a good architecture, I suppose, especially if you expect alot of load, but it would work.

Related

How can you fetch json from an external url with javascript and/or jquery?

I'm trying to get some json from this url : http://api.conceptnet.io/query?rel=/r/UsedFor&limit=3
I have a button that calls the function "jsonplz()" which is supposed to give me an alert with the fetched json.
My javascript looks something like this :
<script src="http://code.jquery.com/jquery-3.3.1.min.js">
</script>
<script>
function jsonplz(){
$.getJSON("http://api.conceptnet.io/query?rel=/r/UsedFor&limit=3?callback=?",function(json){
console.log(json);
});
}
</script>
As you can see, I'm trying to fetch is as jsonp, hence why I added " ?callback=? " at the end of the url, otherwise if I was trying to get it as json, my browser would have blocked me.
Here's the problem : it still doesn't work. I get this error on the firefox console when I call jsonplz() :
Warning : The script from “https://api.conceptnet.io/query?rel=/r/UsedFor&limit=3?callback=jQuery331030366838930478535_1646253265514&_=1646253265515” was loaded even though its MIME type (“application/json”) is not a valid JavaScript MIME type.
Error : Uncaught SyntaxError: unexpected token: ':'
Any solution to either solve this error or any other way to retrieve json from an external url without downloading additional third party software is appreciated
As you can see, I'm trying to fetch is as jsonp, hence why I added " ?callback=? " at the end of the url
The server doesn't support JSONP (and shouldn't, it is a dirty hack with security issues and we have CORS now).
Either:
Change the server to support JSONP (not recommended; see above)
Remove ?callback=? and change the server to grant your JS permission to read the data using CORS
Don't fetch the data directly from the client (e.g. proxy it through your own server).

Receive XML response from Cross-Domain Ajax request with jQuery

I trying to make an ajax request to another domain, it already works, but now I have another problem...
This is my code:
function getChannelMessages(channel) {
jQuery.support.cors = true;
$.ajax(channel, {
cache : true,
type : "get",
data : _channels[channel].request,
global : false,
dataType : "jsonp text xml",
jsonp : false,
success : function jsonpCallback (response) {
console.log(response);
updateChannelRequest(channel);
//getChannelMessages(channel);
}
});
}
As I said, it already works, but the problem is the server returns an XML (Is not my server, is another server from another company - a web service - so I can not change what it returns) and as jsonp expects an json it fails with the error:
SyntaxError: syntax error
<?xml version="1.0"?><ReceiveMessageResponse xmlns="http://q ... />
According to jQuery documentation, adding jsonp text xml should make the magic, converting the response to simple text and then parsing it as XML, but it does not works.
I was already able to make it using YQL, but it has a limit of 10,000 requests per hour, and the system I'm developing will have up to 10 million request per hour. For that same reason, I can not "proxy" in my own server those requests...
FYI: I'm trying to get the newest messages from SQS, so if there is anyway to tell it to return the data as json, it will be easier and better, but I have not find anything either in the documentation...
The plain answer to my question is this: There are only two ways of do this:
Use a proxy. I won't put here all the how-to's to make it, but you can find a lot of information in the web searching for "cors" "cross domains ajax requests" and "yql" (this last is a proxy by Yahoo)
Use CORS. This is Cross-Origin Resource Sharing. That is: activate the server from which you want to get information to sent information to any other domain and to answer to requests from any other domain. To do this you must be the one who manage the server/service.
Those two are the only ways of getting information XML (or any other format) from another domain. To make json cross domain requests:
Use jsonp (Json Padded). I won't explain this (and actually is just extra information since it won't work if the answer from the server is XML - my main problem), cause there is a lot of information on the web.
Unfortunately I was not able to accomplished my goal, cause SQS is not configured to any of this methods... Still, I've got plenty insight of how Cross-Domains Requests works. And I hope this help anyone...

External HTML retrieval

I am trying to get the contents of http://en.wikipedia.org through an ajax call. For this, I am using jQuery. Here is the code:
jQuery.ajax({
url:"http://en.wikipedia.org",
crossDomain: true,
dataType: "jsonp",
jsonpCallback: "myCallback"
});
function myCallBack(data){
console.log("ok");
}
The problem is that I get in Firebug this error:
SyntaxError: syntax error
<!DOCTYPE html>
So I would say that the html content is fetched, although the callback function is not run. At some point it encounters the specified tag, throws this error and stops running the script.
Do you have any idea where the problem might lie?
Is there any other way to get the contents of a html page? I do not want to use iframes, because that means I will not be able to use or modify its contents.
Its because you're Ajax function expects a json response from the provided url and it gives an html response, thats the reason you are getting a syntax error, the same error you will get from the Chrome debugger as well.
Updated:
What you're trying to do is called a Cross-Domain Request.
"For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed."
Reference
Solution:
You can resolve this issue by having a backend script which will the external pages for you. Like a proxy server, which resides the same domain, so you wont have to face the Cross domain issues.
And you can load them, by
$.get(url, success: function(data) { // the url that will fetch the external html page for you, located on the same domain
console.log("ok");
});
Your issue your having here is that you are calling across domains. Allthough you seem to have realised this and are using jsonp for your request, the document you are trying to pull ie wikepedia is not a jsonp document. So as soon as the ajax finds the html tags it will throw an arror, as you have defined that you are expecting a jsonp response.
You cannot just pull other websites data across domain with javascript due to the cross domain issues, if you want to accomplish what you are doing here you will need to use a back end language to get the data.
Usefull link is http://json-p.org/
Hope that helps

Difference jsonp and simple get request (cross domain)

I have to send (and receive) certain data to a server using JQuery and JSON.
Works so far, but not cross domain, and it has to be cross domain.
I looked how to solve this and found JSONP. As far as I see, using JSONP I have to send the callback and the data using GET (JQuery allows to use "POST" as method, but when I inspect web traffic I see it is sending actually GET and everyting as parameter).
JSONP also requires changes in the server, because they are expecting a POST request with JSON data, and they have to implement something to process the JSONP GET request.
So I'm wondering what's the difference between this and sending the data as key value parameters in GET request?
Is the difference the possibility to use a callback? Or what exactly?
Sorry a bit lost... thanks in advance
JSONP is not a form submission. It is a way of telling the server via a GET request how to generate the content for a script tag. The data returned is a payload of JavaScript (not just JSON!) with a function call to a callback which you (by convention) reference in the GET request.
JSONP works because it is a hack that doesn't use AJAX. It isn't AJAX and you should not confuse it for such because it does not use a XMLHttpRequest at any point to send the data. That is how it gets around the Same Origin Policy.
Depending on the browsers you have to support, you can implement Cross-Origin Resource Sharing headers on the server side which will let you use normal AJAX calls across trusted domains. Most browsers (IE8, Firefox 3.5+, etc.) will support CORS.
Another solution you can use if you don't want to use CORS or JSONP is to write a PHP script or Java servlet that will act as a proxy. That's as simple as opening a new connection from the script, copying all of the incoming parameters from your AJAX code onto the request and then dumping the response back at the end of your script.
I found an answer that worked for me with the cross-domain issue and JSON (not JSONP).
I simply used:
header('Access-Control-Allow-Origin: *');
inside my json file (file.php) and called it like this:
var serviceURL = 'http://your-domain.com/your/json/location.php'
$.getJSON(serviceURL,function (data) {
var entries = data;
//do your stuff here using your entries in json
});
BTW: this is a receiving process, not sending.

why my JS can't load document from another server?

I have two web-sites and two files:
provider.com/provide.js
viewer.com/index.html
viewer.com/index.html renders information to the user, and gets this information from provider.com. The file viewer.com/index.html looks like this (jQuery is used):
<script type="text/javascript"
src="http://provider.com/provide.js"></script>
<script type="text/javascript">
provide(function() { alert('works!'); });
</script>
provider.com/provide.js looks like this (I omit unnecessary details):
function provide(callback)
{
$.ajax(
{
'url': 'http://provider.com/',
}
);
}
I'm getting this message in all browsers: Failed to load resource: cancelled.
I have a feeling that I break some security restrictions. Could anyone explain what restrictions, if any. Thanks.
Eventhough the provide.js file is loaded from the provider domtain, it's still loaded in the context of the HTML page, so it's in the viewer domain. When the code tries to make the AJAX call to get information from the provider domain, you run into the cross domain limitation.
You can't use AJAX to load information across domains. However you can use JSONP as data format, then the ajax method will not do an AJAX call, instead it will use a script tag to load the information, which is allowed.
You can't request Javascript to send requests cross domain, for security reasons.
You can however make the request to the server which can retrieve the files and print the results for you, that Javascript can then request.
A brief introduction to the same-origin policy, described in other answers, can be found here:
http://en.wikipedia.org/wiki/Same_origin_policy

Categories