I am trying to display an html file in my js-code.
It is an ordinary html file that I would like to see. I have already created an IFRAME for this, but somehow I cannot go further...
This is my code fragment:
var controlAddIn = document.getElementById('controlAddIn').src = 'index.html';
So the file I want to call is "index.html". But it is not working.
If I call it in that way:
var controlAddIn = document.getElementById('controlAddIn').srcdoc = '<div><meta charset="UFT-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></div>';
It is working, but taht makes it very hard to read...
Do you have an idea, how I can call my entire code at this point, also multiline?
The both file should be same path if you are calling like that
else you have call the correct path
var controlAddIn = document.getElementById('controlAddIn').src = 'index.html';
save this file in index.html path and open it on browser
<script type="text/javascript">
function newSite() {
document.getElementById('myIframe').src = "index.html"
}
</script>
<input type="button" value="Change site" onClick="newSite()" />
<iframe id="myIframe" src="http://google.com/" ></iframe>
You Could use XMLHttp request to get Html File Content this code async
function httpGet(theUrl,callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, true ); // false for synchronous request
xmlHttp.send( null );
xmlHttp.onreadystatechange = function() {
callback(xmlHttp.responseText);
};
}
var controlAddIn;
httpGet("index.html",function(content){
controlAddIn = document.getElementById('controlAddIn').src =content;
});
Related
Im trying to create an automated system for HTML page handling where I will be able to change the contents
of a<div> inside <body> by writing into an external .txt file and uploading it to the server. Im still an early student in university
and I havent learned PHP and JQuery yet. So I am trying to accomplish this by using only Javascript and HTML.
I just need a way for whatever I write inside the .txt file to be written again inside the <div class="CONTENT" id="target"> which is inside the <body> automatically. Any thoughts and suggestions are greatly appreciated!
You can solve your problem by using the FileReader.
Have a look to
this answer.
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsText(file);
}
function displayContents(contents) {
var element = document.getElementById('target');
element.textContent = contents;
}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
<html>
<head></head>
<body>
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<div id="target" class="CONTENT"></div>
</body>
</html>
You can make an AJAX call for the text file and take the response from that call and set that as the .textContent of the div. Here's an example (see comments inline):
const output = document.getElementById("output");
// Create XHR object
var xhr = new XMLHttpRequest();
// Configure the request (substitute a URL
// to the file below)
xhr.open("GET", filePathHere, false);
// Set up the callback for when the response has
// been recieved
xhr.onreadystatechange = function (){
if(xhr.readyState === 4) {
// Was the request successful?
if(xhr.status === 200 || xhr.status == 0) {
// Populate the <div> with the response text
output.textContent = xhr.responseText;
}
}
}
xhr.send(null); // Make the call
<div id="output"></div>
I am trying to make an API call and display that data on my HTML page. Currently no data is displayed when the button is clicked, but the API call is made successfully as I can track my usage on another page. My code is below:
<!DOCTYPE html>
<html>
<body>
<h1>API Data</h1>
<div id="container">
<div id="api">Nothing Yet</div>
</div>
<br>
<button type="button" onclick="loadAPI()">Change Content</button>
<script>
function loadAPI() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "API URL with Token here", false);
xhttp.addEventListener("load", loadData);
xhttp.send();
}
function loadData() {
document.getElementById('api').innerText = JSON.parse(this.responseText);
}
</script>
</body>
</html>
No data is displayed because you're not putting the data into the target element.
To insert data into #api, you need to do something like
document.getElementById('api').innerHTML = apiResponse; // no underscore
// or
document.getElementById('api').innerText = apiResponse;
I'll leave it for you to read up on security. https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
Also, XMLHttpRequest is asynchronous unless specified otherwise (in a param). So the most reliable way is to display the data in the load event listener. Your final code should be something like:
// Making a XMLHttpRequest
function loadAPI() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "API URL with Token Here", false);
xhttp.addEventListener("load", loadData);
xhttp.send();
}
// Displaying the data
function loadData() {
document.getElementById('api').innerText = this.responseText;
}
Note if your response is in JSON, you need to JSON.parse(this.responseText) to access the array/objects.
I had url which looks like http://localhost/dashboard/index.php?id=1 so that i would pass the value in url as per use and switch the dashboard accordingly. All i wanted is url should be visible like http://localhost/dashboard/index.php or even http://localhost/dashboard/index.php/1. I want to hide or replace a url string(for visibility) and not to redirect which i tried using htaccess. can we do that using JavaScript??
You can push state in browser history javascript. This will change your current page's url without redirecting to new url. Try below code in page load event.
history.pushState("", "", "1");
You can use AJAX to get your data from the php file and display the content on your browser.
This will avoid redirection and also the url will remain clean.
Haven't tried it but here's what you can do:
<!DOCTYPE html>
<html>
<body>
<p><span id="dashboardView"></span></p>
<span class="btn" val="1" onclick="showDashboard(this)">Dashboard 1</span>
<script>
function showDashboard(elem) {
var xhttp;
var val = elem.getAttribute("val");
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("dashboardView").innerHTML = this.responseText;
}
};
xhttp.open("GET", "dashboard/index.php?id="+val, true);
xhttp.send();
}
</script>
</body>
</html>
var urlStr = 'http://localhost/dashboard/index.php?id=1';
var nextURL = urlStr.replace("?", "");
alert(nextURL);
I made an html website that will be running in a CD-R (this will be a manual).
I have the page created and everything is working good, but at this moment I'm having some problems for opening a XML file.
My question is, is this possible, since It will be running in a CD Drive?
Thank you
This is what I have:
function testing()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "teste.txt", true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
var allText = rawFile.responseText;
alert(allText);
}
else
alert("erro no xml");
}
rawFile.send();
}
This works fine in for example: localhost/path
But i want it to work in a path like c:\path\
If you don't mind modifying your source files a little bit by turning it into JSON, you could use JSONP. Here's a simple example:
<button onclick="go();">Click me</button>
<script type="text/javascript">
function go() {
var scriptTag = document.createElement("script");
scriptTag.src = "someText.js";
document.getElementsByTagName("body")[0].appendChild(scriptTag);
}
function jsonCallback(txt) {
console.log(txt);
}
</script>
File: someText.js:
jsonCallback("Hello World!");
The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request