Getting data from Google docs into Javascript - 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

Tried this on my own server - got a following CORS error on the browser's console:
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.

When I run the code it works, fills the input with the csv file value. When I try to run the link on How do you Import data from a Google Spreadsheet to Javascript? got cross origin block from my browser.
If you can't run the script below you should try allowing CORS on your browser or perhaps try with ajax.load to get the file.
<html>
<head>
<title>
</title>
<script type="text/javascript">
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);
}
</script>
</head>
<body onload="Data();">
<table>
<form name="Team">
<tr>
<td>
<input size="19" name="tName" readonly>
</td>
</tr>
</form>
</table>
</body>
You should see it something like:

Related

php / Javascript / Ajax loading content does not work

I'm trying to load content from a php file which name is "include.php" to a in another php file which name is "index.php". But the loading does not work. The code is as below:
The file: index.php
<header>
<script type="text/javascript">
function load(){
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechage = function (){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById(adiv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'include.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="submit" value="Submit" onclick="load();">
<div id="adiv"></div>
</body>
The File: include.php
<?php
echo 'Hello!';
?>
Thanks.
If what you are doing is the way you describe then this is simpler:
<header>
<?php include("include.php") ?>
</head>
<body>
<input type="submit" value="Submit" onclick="load();">
<div id="adiv"></div>
</body>
If you want to get result from include.php into JavaScript then you'll probably be better using ajax.
By the way, if you are planning a "universal header" for all your PHP files, you don't need to echo it just write it as normal HTML with any necessary PHP tags
Should it not be document.getElementById("adiv").innerHTML = xmlhttp.responseText;? Notice the quotes.
....xmlhttp.onreadystatechage = function (){
if(xmlhttp.readyState == 4 && xmlhttp.st...
Check the spelling onReadyStateChange.

AJAX call reloads the current page

I am trying to update a div with information received from a server periodically. The code below will receive the correct information from the server, append it to the divs text, then reload the page/clear out the div.
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<script type='text/javascript'>
function exec(command){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = document.getElementById("txtHint").innerHTML + "<br/><br/>" + xmlhttp.responseText;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "HAS-sync.php", true);
xmlhttp.send()
}
</script>
<style type="text/css">
.auto-style1 {
margin-top: 0px;
}
</style>
</head>
<body>
<table style="width: 100%">
<tr>
<td style="width: 141px; height: 390px">Managers<br /> DHTs</td>
<td name="targetThing" style="height: 390px">
<form onsubmit="exec()">
<input class="auto-style1" name="Text1" type="text">
<input type="submit">
</form>
<br />
<div id="txtHint" style="border:1px solid black;width:50%;height:50%"></div>
</td>
</tr>
</table>
</body>
</html>
How can I get this to simply append the result of the ajax call to the divs text, instead of clearing it completely?
First move the onsubmit to the form tag instead of the input as said in the comment.
<form onsubmit="updateTxt(this.value);return false">
You need to append the response text instead of overwriting what is already in innerhtml.
document.getElementById("txtToUpdate").innerHTML += xmlhttp.responseText;
Right now, you are overwriting the HTML using the = assignment. You need to append it, instead, using +=:
document.getElementById("txtToUpdate").innerHTML += xmlhttp.responseText;
Use
var txtToUpdate = document.getElementById("txtToUpdate");
txtToUpdate.innerHTML = txtToUpdate.innerHTML + xmlhttp.responseText;
You need to return false in your onsubmit handler so the browser knows you've handled the request and it should not proceed. This can be done in a couple ways:
Add return false; after exec() in your binding:
<form onsubmit="exec();return false;"><!-- ... --></form>
or, Modify your binding to be return exec() and have the method return false;:
<script>
function exec(){
/* ... */
return false;
}
</script>
<form onsubmit="return exec()"><!-- ... --></form>
As an aside, you should consider moving away from binding javascript using attributes and start using addEventHandler (and alike) to keep a clear separation of concerns.

Html/Javascript image does not take image of type pnm

I need an advice for an issue with html/javascript images. It seems that is not possible to load images of type pnm.
I did test the following example code with Chrome, Internet Explorer and Firefox. It always produces the same problem. Images of type jpg, png, etc. are loaded and displayed correctly. For images of type pnm the onload function of the image never gets called. Therefore I assume that this image type cannot be loaded.
Images of type pnm are described as: image/x-portable-anymap;base64
Please see this piece of code:
<!doctype html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>Image preview example</title>
<script type="text/javascript">
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
console.log("image now loading");
document.getElementById("uploadPreview").onload = function() { console.log("image successfully loaded");};
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
function loadImageFile() {
console.log("image selected");
if (document.getElementById("uploadImage").files.length === 0) { return; }
var oFile = document.getElementById("uploadImage").files[0];
oFReader.readAsDataURL(oFile);
}
</script>
</head>
<body>
<form name="uploadForm">
<table>
<tbody>
<tr>
<td><img id="uploadPreview" style="width: 100px; height: 100px;" alt="Image preview" /></td>
<td><input id="uploadImage" type="file" name="myPhoto" onchange="loadImageFile();" /></td>
</tr>
</tbody>
</table>
<p><input type="submit" value="Send" /></p>
</form>
</body>
</html>
I wonder about this behaviour since pnm ist the most simple and most straight forward image format that exists. It only consists of sizes and pixel data.
Does anybody know how to alter the example code in order to make it work for pnm images?
First price would be a code change. Second price a free browser plugin. I simply would not like to use an additional library or third party code.
Any code correction, no matter how calculation-intensive it is, is welcomed.

AJAX Change HTML Content

I'm trying to change the content of a div with Ajax, however nothing happens... could someone help see what I'm doing wrong?
As far as i can see I'm not missing anything, but the buttons don't connect through. I am running XAMPP and apache is turned on.
Index Page
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="author" content="Malecia Legodi">
<meta name="description" content="Reload Website">
<script language="JavaScript" src="javascript.js"></script>
</head>
<body style="background-color:green">
<div>
<nav>
<table>
<tr>
<td>
<input type="button" id="home" value="Home"/>
</td>
<td>
<input type="button" id="contact" value="contact" />
</td>
</table>
</nav>
<section>
<div id="content" >
<h1>Content Review Summary</h1>
<p>
aaa...
</p>
<p>
bbb...
</p>
</div>
</section>
<footer align="center">© Reload Website</footer>
</div>
</body>
</html>
contact page:
<h1>Content Review Summary</h1>
<p>
ccc...
</p>
<p>
ddd...
</p>
Javascript.js
function initiate(){
content = document.getElementById('content');
var home = document.getElementById('home');
var contact = document.getElementById('contact');
home.addEventListener('click', readHome, false);
contact.addEventListener('click', readContact, false);
}
function readHome(){
var url = "home.html";
var request = new XMLHttpRequest();
request.addEventListener('load', showContent, false);
request.open("GET", url, true);
request.send();
}
function readContact(){
var url = "contact.html";
var request = new XMLHttpRequest();
request.addEventListener('load', showContent, false);
request.open("GET", url, true);
request.send();
}
//function showContent() to add data into your
function showContent(e){
//add data to secContent
content.innerHTML = e.target.responseText;
}
//use the listener to load your initiate() function
window.addEventListener('load', initiate, false);
change the div id content to secContent"
Also change:
content = document.getElementById('content');
to
content = document.getElementById('secContent');
As well as:
content.innerHTML = e.target.responseText;
to
secContent.innerHTML = e.target.responseText;
Your javascript's last couple of blocks of code are exactly alike to an example I was given at college (Although the example in question was only reading a single .txt file rather than several htmls it had the same problem) . I managed to get it to work by the method mentioned above. Hopefully it will help you as well.

Issue with XMLHttpRequest request

I have html page pulling data from another page using ajax.
The code works fine on firefox but gives an access denied on xhr.open("...")in IE and Chrome.
The sample code is as shown.
<!DOCTYPE html>
<html>
<head>
<script type="text/Javascript">
function changeContent(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET",url,false); //Access denied on this line
xhr.send();
var roster = document.getElementById("roster");
roster.innerHTML=xhr.responseText;
}
</script>
</head>
<body>
<img src=images/logo_990x80.png width=1300" height="80" />
<div class="buttonBar">
<input type="button" value="data" onclick="changeContent('data.html')"/>
</div>
<div id="roster" class="roster">
Click on the buttons above to choose a roster
</div>
</body>
</html>
The data.html contains a simple table with 2 rows of data.
How can I solve this issue.
Edit : Code shown below works on IE and firefox but still has the same issue in Chrome.It seems ActiveX works on local files for Ajax.
<!DOCTYPE html>
<html>
<head>
<script type="text/Javascript">
function changeContent(url)
{
var xhr = false;
if(location.protocol=="file:")
{
if(!xhr)try{ xhr=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xhr=false;}
if(!xhr)try{ xhr=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xhr=false;}
}
else
{
if(!xhr)try{ xhr=new XMLHttpRequest(); }catch(e){xhr=false;}
}
xhr.open("GET",url,false); //Access denied on this line only in Chrome
xhr.send();
var roster = document.getElementById("roster");
roster.innerHTML=xhr.responseText;
}
</script>
</head>
<body>
<img src=images/logo_990x80.png width=1300" height="80" />
<div class="buttonBar">
<input type="button" value="data" onclick="changeContent('data.html')"/>
</div>
<div id="roster" class="roster">
Click on the buttons above to choose a roster
</div>
</body>
</html>
Any tips for chrome.
This is usually caused by trying to use XMLHTTPRequest without using an HTTP URI.
Firefox supports XHR over file: scheme URIs, most browsers do not.
Run your page through a web server if you want to use Ajax.

Categories

Resources