Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data from Google docs into Javascript

I try to get data from google spreadsheets and everything is allright when I'm testing html page locally. But when I load my html file and javascript file into server nothing works.

Here is the code of html file "page.htm":

<html>
<head>
<title>
</title>
<script type="text/javascript" src="teams.js" >
</script>
</head>
<body
onload= "Data();">
<table>             
    <form name="Team">
    <tr>                
        <td>
        <input  size="19"  name="tName" readonly >
        </td>               
    </tr>
    </form>
    </table>
</body>
</html>

And js file "teams.js":

function Data() {
var url="https://docs.google.com/spreadsheets/d/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/pub?&gid=0&range=A1&output=csv";

xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status==200){
      document.Team.tName.value = xmlhttp.responseText;
    }
  };
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
}

Google doc

like image 422
Rm1 Avatar asked Mar 23 '26 03:03

Rm1


1 Answers

Tried this on my own server - got a following CORS error on the browser's console: CORS error

This means that you cannot directly access the url with your browser, because the Google's server is not sending back a required header field that would allow this.

A way around this is to use an alternative API, that can provide us with JSONP format output for the Google Spreadsheet:

So consider this JavaScript:

function Data(response) {
  document.Team.tName.value = response.feed.entry[0].gs$cell.$t;
}

And the following HTML:

<html>
<head>
<title>
</title>
<script type="text/javascript" src="teams.js" >
</script>
</head>
<body>
<table>             
    <form name="Team">
    <tr>                
        <td>
        <input  size="19"  name="tName" readonly >
        </td>               
    </tr>
    </form>
    </table>
<script src="https://spreadsheets.google.com/feeds/cells/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/1/public/values?alt=json-in-script&callback=Data&range=A1"></script>
</body>
</html>

And it should work perfectly.

This works as, rather than your won code, the Google's own server calls the Data function with the proper data - a method called JSONP that allows cross-domain data requests. Requesting data from another domain is blocked by default in the browsers. The only exception is the file:// protocol, which allows some requests to any domains, as there is no origin domain to match the rules. This explains why your code worked on the local, but not after it had been uploaded to the server.

like image 147
jehna1 Avatar answered Mar 25 '26 17:03

jehna1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!