I have some troubles to read a number from a text file with JavaScript.
setInterval("readTextFile()", 500);
function readTextFile() {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "zoom.txt", false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
document.getElementById('boldStuff').innerHTML = allText;
writeln(allText);
}
}
}
rawFile.send(null);
}
The goal is to read a value into zoom.txt every 500ms, but this code doesn't work.
The value from the text file isn't refresh on F5 but only when I open (or refresh) zoom.txt in my browser.
I find something strange, this code works the first time I used it on Midori. Could you help me please ?
Thanks,
EDIT :
I tried that :
setInterval(readTextFile, 500);
setInterval(test, 500);
function readTextFile()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "zoom.txt", false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
document.getElementById('boldStuff').innerHTML = allText;
}
}
}
rawFile.send(null);
}
function test(){
document.getElementById('boldStuff').innerHTML = '';
}
My value is blinking on the screen but don't change even if I modify it.
First parameter to the setInterval should be a function and not function call.
setInterval(readTextFile, 500); //No need of quotes
If it is fetching the data from the text file on page refresh means that your code is working fine.
Now, you need to change the text in your text file so that it will get new value from the text file.
To check the content every interval you need to empty the html of your div like,
function readTextFile() {
// empty the div first to get the new value from text file
document.getElementById('boldStuff').innerHTML = '';
...
Okay, I empty the cache of Firefox and avoid to use it and the code is working fine.
Related
I have a program that should pick a random line from a local text file, but it seems to not be working.
Here's the code:
<html>
<head>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<h1 id = "gen">Alt Info: </h1>
<script>
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;
var split = allText.split('\n')
var randomNum = Math.floor(Math.random() * split.length);
var randomLine = split[randomNum]
console.log("All Lines\n"+allText)
console.log("Line Numebr\n"+(randomNum+1))
console.log("Random Line\n"+randomLine)
}
}
}
rawFile.send(null);
}
readTextFile("alts.txt");
</script>
<button type="button" class=button onclick=document.getElementById("gen").innerHTML = randomLine;>Generate</button>
The code above should pick a random line from the 'alts.txt' text file and then when the generate button is clicked it should display that random line to the screen. Instead when I click the generate button, nothing happens.If someone could help me that would be awesome!
Your button is using an inline handler that's trying to reference a variable not in the global scope.
Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
The other problem is that #showText does not exist - just remove that line from your script.
You have a couple options here. One is to make randomLine a global variable so that it can be referenced by the button on demand - which isn't recommended:
<script>
var randomLine;
function readTextFile(file)
// ...
var randomNum = Math.floor(Math.random() * split.length);
randomLine = split[randomNum]
But in addition to that, it would be better to remove the inline handler, and add a click listener to the button properly:
document.querySelector('button').addEventListener('click', () => {
document.getElementById('gen').textContent = randomLine;
});
Or, even better, don't create a global variable at all; keep the line defined only where it's needed, which is inside the listener:
(() => {
var randomLine;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "alts.txt", false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200) {
var allText = rawFile.responseText;
var split = allText.split('\n')
var randomNum = Math.floor(Math.random() * split.length);
randomLine = split[randomNum]
console.log("All Lines\n" + allText)
console.log("Line Numebr\n" + (randomNum + 1))
console.log("Random Line\n" + randomLine)
}
}
}
rawFile.send(null);
const gen = document.getElementById('gen');
document.querySelector('button').addEventListener('click', () => {
if (randomLine) gen.textContent = randomLine;
else gen.textContent = 'Not retrieved yet';
});
})();
(or use fetch and Promises to handle the asynchronicity instead)
I need an image to change when it's clicked and to load a URL without anything visual changing on the page. I only need a total of two images and each image will be associated with one URL. I was able to replicate the example of onclick image change located at:
http://www.paulgriffiths.net/program/javascript/otherbasic1.php
For example: I want the image of the earth to change to mars and load URL #1. Then when mars is clicked on I want it to load back the picture of earth and load URL #2. I want the URL to load in the background and not change the images of earth and mars.
What do I add to the ".js" file below to accomplish this?
var newsrc = "mars.jpg";
function changeImage() {
if ( newsrc == "mars.jpg" ) {
document.images["pic"].src = "/images/program/js/forms/mars.jpg";
document.images["pic"].alt = "Mars";
newsrc = "earth.jpg";
}
else {
document.images["pic"].src = "/images/program/js/forms/earth.jpg";
document.images["pic"].alt = "Earth";
newsrc = "mars.jpg";
}
}
I used a boolean instead of testing strings but this should help you.
function loadCommand(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// if successfull
} else {
// if not successfull
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
var isOn = false;
var img = document.getElementById("pic");
// change handler
var loadImage = function() {
if (isOn) {
loadCommand("http://x.x.x.x/cmd/DOFF");
img.src = "/images/program/js/forms/mars.jpg";
img.alt = "Mars";
} else {
loadCommand("http://x.x.x.x/cmd/DON");
img.src = "/images/program/js/forms/earth.jpg";
img.alt = "Earth";
}
};
// set up event handler
img.onclick = function() {
// potentially send window to new location with window.location=<host>/cmd/DOFF or something similar
// or just change state
isOn = !isOn;
loadImage();
};
// load initial image
loadImage();
How do I add the slideDown jquery animation when I knew message is loaded? Perhaps I can't with my method for loading... A file takes user input and inserts into database. Another file pulls from database onto chatbox and styles.
Javascript Code:
var form = document.querySelector('form[name="chatbox"]');
form.addEventListener("submit", function (event) {
event.preventDefault();
});
function submitChat() {
if(chatbox.message.value == '') {
alert('Error: Missing Fields.');
return;
}
var message = chatbox.message.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4&&xmlhttp.status==100) {
document.getElementById('chatlog').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','chat.php?message='+message, true);
xmlhttp.send();
chatbox.reset();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlog').load('logs.php');}, 200);
});
Please let me know if you need the PHP attached.. Thanks for the help! :)
i got a problem with JS:
On line 1 to 4 I take all "a"-Elements from the DOM and get their hrefs.
later I want to reload the URL via AJAX, but the href does not arrive correctly... Whats wrong?
$(document).ready(function(){
$('a').click(function(e){
ajaxReload($(this).attr('href'));
e.preventDefault();
});
});
function ajaxReload(href) {
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", href, true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState != 4) {
document.write('loading');
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('hello');
//alert('getting '+xmlhttp.status+' for '+href);
var pureHTML = xmlhttp.responseText;
var ajaxstart = pureHTML.indexOf('<!-- AJAX START -->');
var ajaxend = pureHTML.indexOf('<!-- AJAX END -->');
var ajaxContent = pureHTML.substring(ajaxstart, ajaxend);
var writeContent = document.getElementById('content');
writeContent.innerHTML = ajaxContent;
}
}
xmlhttp.send(null);
}
Sorry if I've misunderstood your code. I think that you simply need to (at least approximately) just remove code as commented below:
//$('a').click = function(href) {
var pureHTML = xmlhttp.responseText;
var ajaxstart = pureHTML.indexOf('<!-- AJAX START -->');
var ajaxend = pureHTML.indexOf('<!-- AJAX END -->');
var ajaxContent = pureHTML.substring(ajaxstart, ajaxend);
$("content").html(ajaxContent);
// ajaxReload(href); //this would cause a loop?
// return false;
//}
To answer your later question - you can change your event propagation handling to:
$(document).ready(function(){
$('a').click(function(e){
ajaxReload($(this).attr('href'));
e.preventDefault();
});
});
And for the further comments, maybe try changing your:
document.write('loading');
To:
$("content").html(xmlhttp.status); //so now you can see the loading status for testing
Okay, this is following on from my previous question reguarding performing a simple ajax request that, once the request has returned a readyState of 4 and a status of 200 it inserts the response into a div and slides it down nicely. I don't want it to be performed using a toolkit such as jQuery or scriptalicious.
here is the original question:
Ajax with slide effects onready witout using a toolkit
So far I have managed to get it all working quite nicely. However I have the problem that, the text returned is shown and then the div expands. I need it to work with the div and text expanding together.
Here is my code
function slideDown()
{
document.getElementById('slideDiv').style.visibility = 'hidden';
xmlhttp.open("GET", "parse.php?what=main", true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('butt').value = 'hide';
document.getElementById('slideDiv').innerHTML = xmlhttp.responseText;
document.getElementById('slideDiv').style.display = 'block';
var fHeight = document.getElementById('slideDiv').offsetHeight;
document.getElementById('slideDiv').style.height = '0';
document.getElementById('slideDiv').style.visibility = 'hidden';
function timeIt()
{
function bar()
{
timeSlide(fHeight);
}
setTimeout(bar, 10);
}
timeIt();
}
}
xmlhttp.send(null);
}
function timeSlide(fHeight)
{
var fHeight;
var diff;
document.getElementById('slideDiv').style.visibility = 'visible';
var cHeight = document.getElementById('slideDiv').clientHeight;
if (cHeight < fHeight)
{
cHeight = cHeight + 3;
document.getElementById('slideDiv').style.height = cHeight+'px';
function timeIt()
{
function bar()
{
timeSlide(fHeight);
}
setTimeout(bar, 10);
}
timeIt();
}
else
{
endSlide();
}
}
I think this is happening due to using the following to put the returned get request into the div.
document.getElementById('slideDiv').innerHTML = xmlhttp.responseText;
Can someone please put me in the correct direction with this? I'm not particularty good with JavaScript and I'm probably going the complete wrong way about it so any pointers would be great! Thanks in advance!
It's hard to say without seeing it in action but try adding this:
document.getElementById('slideDiv').style.overflow = 'hidden';