I'm trying to Figure out how to replace HTML text using js code,
the goal of it is the read a "1.txt" file with a name and replace the HTML text (Replace me!!)
if anyone can help me and point me in the right direction.
here is what I have now
<body class="htmlNoPages">
<div id="main"><p>Replace me!!</p></div>
</body>
<script type="text/javascript" id="gwd-init-code">
function load() {
// var text = ('test 123')
var file = new XMLHttpRequest();
file.open(GET,'file:///d:/1.txt', true);
file.responseType =Text;
file.onreadystatechange = function() {
if (file.readyState === 4) { // Makes sure the document is ready to parse
if (file.status === 200) { // Makes sure it's found the file
text = file.responseText;
}
}
}
let element = document.querySelector('#main');
element.innerHTML = text;
}
window.onLoad = load();
</script>
I did it like this
var TxtFile = new XMLHttpRequest();
TxtFile.onreadystatechange = function () {
var allText = "Uw browser is niet compatibel of u heeft uw java script disabeld staan";
if (TxtFile.readyState === XMLHttpRequest.DONE && TxtFile.status == 200) {
allText = TxtFile.responseText;
allText = allText.split("\n").join("<br>");
}
document.getElementById('planning').innerHTML = allText;
}
TxtFile.open("GET", 'File location', true);
TxtFile.send(null);
Related
Please help me!
I have Script:
var titles =[];
titles.push('I want file txt in here');
I can not get the txt file into the titles.push, so I need some help!
function readTextFile(){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "text.txt", false);
rawFile.onreadystatechange = function (){
if(rawFile.readyState === 4){
if(rawFile.status === 200 || rawFile.status == 0){
var allText = rawFile.responseText;
console.log(allText);
}
}
}
rawFile.send(null);
}
I do not have a text file ready to show so I used what you should be reading about XMLHttpRequest.responseText you do not want to use onreadystatechange but maybe xhr.onload I left some console.log()s in the code so you can play around with it.
var titles =[];
titles.push('I want file txt in here');
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText', true);
xhr.responseType = 'text';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
// not needed but do not want to push the entire page
// to titles so lets find just one title
var parser = new DOMParser();
var doc = parser.parseFromString(xhr.responseText, "text/html");
var title = doc.querySelector('h1');
// console.log(title);
titles.push(title);
logTitles();
}
}
};
xhr.send(null);
function logTitles() {
console.log(titles);
};
I'd like to find the javascript/Jquery equivalent of this python code but I'm unable to :
config_array = open("config.txt").read().splitlines()
This opens the text file "config.txt" and stores each line into an array while removing '\n' at the end of line. For instance :
config.txt :
first line\n
second line\n
third line\n
gives me
config_array[0] == "first line"
config_array[1] == "second line"
config_array[2] == "third line"
How to achieve the same with javascript and Jquery ? Thanks
You can do it with ajax.
function readTextFile(file)
{
var txtFile = new XMLHttpRequest();
txtFile.open("GET", file, false);
txtFile.onreadystatechange = function ()
{
if(txtFile.readyState === 4)
{
if(txtFile.status === 200 || txtFile.status == 0)
{
var result = txtFile.responseText;
result.split("\n");
console.log(result);
}
}
}
txtFile.send(null);
}
readTextFile('path to txt file')
The simplest way would be splitting the response from the file on \n see below
I assume that there are only three line in the file you are reading
$(document).ready(function () {
$.get('your_file.txt', function (response) {
a = response.split("\n");
console.log(a[0], a[1], a[2]);
})
})
You do like below
var myArray = new Array;
$.get('example.txt', function(data) {
//Bind in div
$('#div').html(data.replace('\n',''));
//insert in Array
myArray = data.split('\n');
});
The OP requires reading from a text file and removing the string '\n'. Thus,
$(document).ready(function () {
function readTextFile(file) {
const rawFile = new XMLHttpRequest();
let content = null;
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status === 0) {
content = rawFile.responseText;
}
}
};
rawFile.send(null);
return content;
}
let textFile = 'config.txt';
// read text file
let rtf = readTextFile(textFile);
// replace string \n
let rnl = ta.replace(/\\n/g, '');
// store each line in an array
console.log(rnl.split('\n'));
}
I am trying to load some data from my JSON file using AJAX. The file is called external-file.json. Here is the code, it includes other parts that haven't got to do with the data loading.The part I'm not sure of begins in the getViaAjax funtion. I can't seem to find my error.
function flip(){
if(vlib_front.style.transform){
el.children[1].style.transform = "";
el.children[0].style.transform = "";
} else {
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
}
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');
el.addEventListener('click', flip);
var word = null; var explanation = null;
var i=0;
function updateDiv(id, content) {
document.getElementById(id).innerHTML = content;
document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
function counter (index, step){
if (word[index+step] !== undefined) {
index+=step;
i=index;
updateDiv('the-h',word[index]);
updateDiv('the-p',explanation[index]);
}
}
var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
r.onload = function() {
if(this.status < 400 && this.status > 199) {
if(typeof callback === "function")
callback(JSON.parse(this.response));
} else {
console.log("err");// server reached but gave shitty status code}
};
}
r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}
r.send();
}
function yourLoadingFunction(jsonData) {
word = jsonData.words;
explanation = jsonData.explanation;
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
// then call whatever it is to trigger the update within the page
}
getViaAjax("external-file.json", yourLoadingFunction)
As #light said, this:
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
Should be:
function getViaAjax(url, callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", url, true);
I built up a quick sample that I can share that might help you isolate your issue. Stand this up in a local http-server of your choice and you should see JSON.parse(xhr.response) return a javascript array containing two objects.
There are two files
data.json
index.html
data.json
[{
"id":1,
"value":"foo"
},
{
"id":2,
"value":"bar"
}]
index.html
<html>
<head>
</head>
<body onload="so.getJsonStuffs()">
<h1>so.json-with-ajax</h1>
<script type="application/javascript">
var so = (function(){
function loadData(data){
var list = document.createElement("ul");
list.id = "data-list";
data.forEach(function(element){
var item = document.createElement("li");
var content = document.createTextNode(JSON.stringify(element));
item.appendChild(content);
list.appendChild(item);
});
document.body.appendChild(list);
}
var load = function()
{
console.log("Initializing xhr");
var xhr = new XMLHttpRequest();
xhr.onload = function(e){
console.log("response has returned");
if(xhr.status > 200
&& xhr.status < 400) {
var payload = JSON.parse(xhr.response);
console.log(payload);
loadData(payload);
}
}
var uri = "data.json";
console.log("opening resource request");
xhr.open("GET", uri, true);
xhr.send();
}
return {
getJsonStuffs : load
}
})();
</script>
</body>
</html>
Running will log two Javascript objects to the Dev Tools console as well as add a ul to the DOM containing a list item for every object inside the data.json array
When the following code executes it's showing no output. Can anyone tell me where I am going wrong?
html file:
<head>
<script type = "text/javascript">function ajax_get_json()
{
var hr = new XMLHTTPRequest();
hr.open("GET","mylist.json",true);
hr.setRequestHeader("Content-type :application/json",true);
hr.onread
ystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var data = JSON.parse(hr.responseText);
var results=document.getElementById("results");
results.innerHTML = data.user;
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type = "text/javascript">ajax_get_json();</script>
</body>
json file:
{ "user":"John", "age":22, "country":"US" }
XMLHTTPRequest() must be XMLHttpRequest(). The JavaScript file looks like:
function request() {}
request();
HTML
<script src="file.js"></script>
With var data = JSON.parse(hr.responseText); you have on object.
Go through the object:
for(var key in obj) {}
and store key and obj[key] in innerHTML to see a result.
Complete JavaScript file:
function request() {
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText); // object
var results = document.getElementById("results");
results.innerHTML = "";
for(var key in data) {
results.innerHTML += key + " " + data[key] + "<br>";
}
}
}
hr.open("GET", "mylist.json", true);
hr.send();
results.innerHTML = "requesting...";
}
request();
(Please change the title of your question. Be specific!
How to ask)
I have read some of the previous questions on this topic but I really need to be 100% sure!
Is it possible to read from a .txt file on my local system and present it in my HTML-BODY?
I have tried several functions, here is one:
function readFile (path) {
var fso = new ActiveXObject('Scripting.FileSystemObject'),
iStream=fso.OpenTextFile(path, 1, false);
while(!iStream.AtEndOfStream) {
document.body.innerHTML += iStream.ReadLine() + '<br/>';
}
iStream.Close();
}
readFile("testing.txt");
The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY.
Is this possible without having my own server?
You can use a FileReader object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>