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.
Related
Wondering why my XML URL Feed data is not displaying to HTML on the front-end. If I host the static XML in my directory, it works. However, when using a live feed from https://www.prlog.org/news/us/ind/sports/rss.xml, it does not work???
<!doctype html>
<html lang="en">
<head>
<title>Test XML Feed</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-8">Testing XML Feed</h1>
<hr class="my-2">
<div class="row">
<div class="col-12">
<div id="title"></div>
</div>
<div class="col-12">
<div id="description"></div>
</div>
</div>
</div>
</div>
<script>
//Display it
function displayFEED(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
//Call XML Feed with Live URL
xmlhttp.open("GET", 'https://www.prlog.org/news/us/ind/sports/rss.xml', true);
xmlhttp.send();
}
displayFEED(1);
// Call tag names from XML and match ID's
function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("channel");
document.getElementById("title").innerHTML = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
document.getElementById("description").innerHTML = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
}
</script>
</body>
</html>
If the server cooperates, your code using XMLHttpRequest can pull the remote resource; for the sample subdomain below I have configured the header and that way the code run here on stackoverflow.com can access the file fine:
const uri = 'https://cors-resources.liberty-development.net/sample1.xml';
const req = new XMLHttpRequest();
req.open('GET', uri);
req.onload = function(e) {
console.log(req.responseXML);
};
req.send();
But if the server does not cooperate you can't do anything but set up some kind of proxy service on your own site and have it pull the remote URIs with server-side code on your own site while client-side JavaScript simply connects to your own site.
So I'm fairly new to AJAX, I have a simple 3 page project which I am using AJAX to transition between pages.
I have an index.html page which loads all the html / body / scripts etc:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax practice</title>
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<div class="" id="wrapper">
<div class="overlay"></div>
<header>
<nav>
<ul>
<li><a class="aboutBtn" href="main.html">Home</a></li>
<li><a class="aboutBtn" href="about.html">About</a></li>
<li><a class="aboutBtn" href="#">Menu</a></li>
<li><a class="aboutBtn" href="#">Contact</a></li>
</ul>
</nav>
</header>
<div class="page wrapper" id="page">
<div class="circle" id="black"></div>
<div class="circle" id="red"></div>
<div class="circle" id="blue"></div>
<section class="mainSplash main">
<div class="mainSplash__content" id="content">
</div>
</section>
</div> <!-- page -->
</div> <!-- wrapper -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="scripts/index.js"></script>
</body>
</html>
and my 2 pages are:
main.html:
<h1 class="mainSplash__header--h1">Main</h1>
about.html:
<h1 class="mainSplash__header--h1">About</h1>
Here is the AJAX which transitions the pages:
$(document).ready(function() {
var pathname = window.location.pathname; // Returns path only
console.log(pathname);
// $('.mainSplash').css('height',$(window).height() - 60);
$(".aboutBtn").click(function(e) {
e.preventDefault();
var pageTitle = $(this).text();
var pageUrl = $(this).attr('href');
changePage(pageUrl, true, pageTitle);
}); // click
function changePage(url, bool, pageTitle){
$('#page').addClass('fadeOut');
loadContent(url, bool, pageTitle);
}
function loadContent(url, bool, pageTitle){
$.ajax({
url: './' + url,
type: 'get',
contentType: 'html',
success: function(data){
$('#page').one('animationend',
function(e) {
// load content
$('#page').removeClass('fadeOut');
$('#page').addClass('fadeIn');
$('#content').html(data);
//$("html").html(data);
// Change url
if(url != window.location){
window.history.pushState({path: url}, pageTitle, url);
}
});
}
});
}
function removeAnimation(){
$('#page').removeClass('animate');
}
});
So my transitions work fine when I have come from index.html, though when I refresh main.html or about.html, they do not keep the code from index.html (obviously).
My question is:
How do I handle a refresh or back button from my pages without losing the index.html content? Any help or advice is appreciated - thank you in advance.
PS: If anyone knows of any AJAX html page transition examples I would love to know so I can improve my code, as I'm looking for best practice for AJAX transitions!
multi way available to do this but best way is use hash routing. see this plugin 'Routei '.set param in hash route then and get it when click on back button and handel ajax whit this param.
I would suggest using the browser page hash and on navigation check for the given hash and load the corresponding page.
let hash = window.location.hash;
When the hash changes, your browser adds a new history for that page.
On the load of the Site you need to add entry in the history with the command history.pushState and to go back to use the buttons of the browser you will need the EventListener onpopstate
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.
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.
On clicking the links am sending the ajax call to get the response, am able to get the correct response but the script tag inside the response page is not working. how to make it run
This is HTML PAGE
<HTML>
<HEAD>
<link rel="stylesheet" type="text/css" href="css/global.css">
<script type="text/javascript" src="js/ajaxgetter.js"></script>
<script type="text/javascript" src="js/mootools.js"></script>
</HEAD>
<BODY>
<h1>ajax block container</h1>
<div id="container">
<div id="tab_wrapper">
<ul id="tab_list" >
<li>
Number 1
</li>
<li>
Number 2
<br/><br/><br/>
</li>
</ul>
</div>
<br/><br/><br/><br/><br/><br/>
<div id="content_tab">
</div>
</div>
</BODY>
</HTML>
The javascript code
function ajaxenabled(url,param,id)
{
var page_request = false
if (window.XMLHttpRequest){
page_request = new XMLHttpRequest()
}
else if (window.ActiveXObject){
try{
page_request = new ActiveXObject("MSXML2.XMLHTTP")
}
catch (e){
try {
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false;
page_request.onreadystatechange=function(){
if(param!=null)
{
loadpage(page_request, param,id);
}
if(param==null)
{
loadpage(page_request,'',id);
}
}
page_request.open('GET', url, true);
page_request.send(null);
}
function loadpage(page_request,param,id){
var getblock=document.getElementById(id);
if(page_request.status==200) {
getblock.style.display='block';
getblock.innerHTML=page_request.responseText;
if(param!=null)
{
//alert("showed");
}
}
}
Response Page " firstelement.html "
<h1>First Element having ajax call</h1>
<script type="text/javascript">
alert("testing the simple function");
</script>
The Alert present inside Script tab inside the firstelement.html is not triggered ,
You should move that script from inside the HTML file to a .js file and call that script after you have successfully finished the ajax call.
Your HTML file will be:
<HTML>
<HEAD>
<link rel="stylesheet" type="text/css" href="css/global.css">
<script type="text/javascript" src="js/ajaxgetter.js"></script>
<script type="text/javascript" src="js/mootools.js"></script>
<script type="text/javascript" src="js/YOUR_SCRIPT_FILE_HERE.js"></script>
</HEAD>
<BODY>
<h1>ajax block container</h1>
.
.
.
You will of course move the
<script type="text/javascript">
alert("testing the simple function");
</script>
into a .js file you place inside the "js" directory. Remember to do it as a method you can call so the .js file will have something like this
function afterAjaxSuccess(){
alert("testing the simple function");
}
and then in your html file you update your loadpage method like this:
function loadpage(page_request,param,id){
var getblock=document.getElementById(id);
if(page_request.status==200) {
getblock.style.display='block';
getblock.innerHTML=page_request.responseText;
afterAjaxSuccess(); //updated line here
if(param!=null)
{
//alert("showed");
}
}
}
and your HTML page becomes
<h1>First Element having ajax call</h1>
without any script
I just use mootools Request.HTML it will evaluate all the script tags in the returned page and replace the html in an element if the update is set in the options.