Issue with XMLHttpRequest request - javascript

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.

Related

Function with parameter set to default value not working in Internet Explorer but works fine on Firefox

I'm using the updated versions of Firefox 62.0.3 and Internet Explorer 11.0.85. I have a simple code which works on Firefox but not in internet explorer.
The html file get_name.html
<html>
<head>
<title>test onsubmit on ie</title>
<script language="javascript" type="text/javascript" src = "myscript.js"> </script>
</head>
<body>
<form id="formId" action="#" name="getName" onsubmit="return(displayAnswer('Lion'))">
<p><input type="submit" value="SUBMIT" />
</form>
<span style="font-size: xx-large">Name sent to Fucntion: </span><label style="font-size: x-large" name = "displayName" id = "lblName"></label>
</body>
</html>
javascript file myscript.js
function displayAnswer (defaultVal = "Tiger") {
document.getElementById('lblName').innerHTML = defaultVal;
return false;
}
So if you run the html file in Firefox it works perfectly fine and prints the passed argument onto the Label, but it won't work on Internet Explorer
But if i have the function as this
function displayAnswer (defaultVal ) {
document.getElementById('lblName').innerHTML = defaultVal;
return false;
}
Then it works on both browsers. Thanks in advance!
Because IE does not support default parameters.
For more details have a look at the MDN docs.

Loaded html not fetching javascript files

I have a html page which dynamically loads the contents of another html file into a div.
function loadHTML(url, id) {
req = new XMLHttpRequest();
req.open('GET', url);
req.send();
req.onload = () => {
console.log(req.responseText);
document.getElementById(id).innerHTML = req.responseText;
}
}
I call loadHTML("/lib/header/header.html","header") which loads the contents of /lib/header/header.html into the div in the main html <div id="header"></div>
/lib/header/header.html
<script src="/lib/header/header.js"></script>
<link href="/lib/header/header.css" rel="stylesheet">
<header>
<object id="logo" data="/lib/global/Icon.svg"></object>
<span id="auth">
<span class="pair" id="login">
<p>Login</p>
</span>
<span class="pair" id="register">
<p>Register</p>
</span>
</span>
</header>
as you can see, the header.html file also includes a header.css and header.js file. The header.css file gets correctly loaded but the header.js file doesn't.
It's not even listed in the "Network" tab of Chrome developer tools.
I am completely clueless as to why this is happening.
Thanks in advance.

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
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:

getElementByID doesn't working with xmlDoc

I am trying to learn xml and ajax for a school project I am currently working on. I need to create a chat system between two users and because I am still learning I do some "experiments" to see how things work.
I am trying to get information from an xml file and to print the information on but the problem is after I get the xmlDoc. , and press CTRL+SPACE, I don't see that I have any getElement option.
This is the XMLFile:
<?xml version="1.0" encoding="utf-8" ?>
<Conversation>
<Massage>
<To>a</To>
<From>b</From>
<Text>a to b</Text>
<Date>11/12/2014</Date>
</Massage>
<Massage>
<To>b</To>
<From>a</From>
<Text>b to a</Text>
<Date>11/12/2014</Date>
</Massage>
</Conversation>
And this is the html file:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function LoadXMLDoc(FileName) {
var xmlhttp;
if (window.XMLHttpRequest())
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", FileName, false);
xmlhttp.send();
return xmlhttp.response;
}
</script>
</head>
<body>
<script>
function Function() {
var xmlDoc = LoadXMLDoc("XMLFile.xml");
}
</script>
<form id="form1" runat="server">
<div>
<center>
<h1> Chat </h1>
<div id="Box" style="position:relative;height:200px;width:400px;border-width:2px;border-style:solid;border-color:black">
<div id="Conversation">
</div>
<div id="Write" style="position:absolute; bottom:0;right:0;">
<input type="text" id="MassageText" />
<button id="SendMassageButton" causesvalidation="False" type="submit" onclick="Function(); return false">Send</button>
</div>
</div>
</center>
</div>
</form>
</body>
</html>
I am learning with w3school and I don't see any problems here.
Maybe there is a problem with the intellisense? I had an error message about that when I was trying to create a for loop.
B.T.W sorry if I have a bad english.

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.

Categories

Resources