Unable to read text file in Javascript - javascript

I have a local text file present in the location /home/myname/Desktop/iot/public/sensordata.txt. This file has to be read in JavaScript when a button is clicked on a web page. My code is given below:
<html>
<head>
<title>Humidity</title>
</head>
<body>
<h3>Humidity page</h3>
<table>
<tr>
<td>
<button type="button" onclick="humidgraph('public/sensordata.txt','chartContainer')">View live humidity data</button>
</td>
</tr>
</table>
<p><div id="chartContainer" style="height: 300px;width= 100%;"></div></p>
<script type="text/javascript">
function humidgraph(datasource,divid){
var i=0;
var xVal,yVal;
var humidity=[],time=[],dps=[];
var fileread=false;
var obj=document.getElementById(divid);
if(window.XMLHttpRequest){
fileread=new XMLHttpRequest();
}else if(window.ActiveXObject){
fileread=new ActiveXObject("Microsoft.XMLHTTP");
}
if(fileread){
fileread.open("GET",datasource);
document.getElementById("chartContainer").innerHTML=fileread.responseText;
}
fileread.onreadystatechange=function(){
if((fileread.readyState===4 || fileread.readyState===0) && fileread.status===200){
var text=fileread.responseText;
text.split(/\n/).forEach(function(item){
humidity.push(Number(item.match(/Humidity(.\d+[.]\d+)/)[1]));
});
text.split(/\n/).forEach(function(item){
time.push(Number(item.match(/time(.\d+[.]\d+)/)[1]));
});
}
}
while(i<time.length){
xVal=time[i];
yVal=humidity[i];
dps.push({x: xVal,y: yVal});
i++;
}
}
</script>
</body>
</html>
However, no data is being printed on the html page, even though innerHTML is being used. Is there something wrong with my file path? Please help.

You need to run a webserver and make the get request to a URI on that server, rather than making the get request to a file (you get a "cross origin requests" error).
Then change:
humidgraph('public/sensordata.txt','chartContainer')
to read something like:
humidgraph('http://localhost/public/sensordata.txt','chartContainer')
and the initial request page needs to be loaded from that server as well.
Additionally you should do your request in the below order:
fileread.onreadystatechange=function (){
...
};
...
fileread.open("GET", datasource);
fileread.send();

Related

Getting a 404 error when when trying to run html page

I am trying to send over a string from PHP to a variable in JSON. But each time the page loads I get a 404 resource error for some reason. I don't understand what is happening and why I keep getting this error. I get the error after the webpage runs through the script part of the code. The way I check this out was using the dev kit in google chrome.
I'm running PHP through Microsoft IIS.
GettingFileInfo.php
<?php
//Calls the getFileInfoMainFunction
getFileInfoMainFunction();
//Function : sscaddir
//Parameters : $dir
//Returns : array
//Description : This function takes an array where we get rid of the dots
function sscandir($dir)
{
return array_values(array_diff(scandir($dir),array('..','.')));
}
function getFileInfoMainFunction(){
//variables
$implodedFilesEqual;
$toJson;
//C:\localwebiste\holmes-e-joesph-r
$fileDirectory=dirname(__FILE__);
//now we are in the MyFilesDirectory
$fileDirectory.="\MyFiles";
//store all the files in the filedirectory in an array
$files=sscandir($fileDirectory);
//The '|' delimter
//This is the string that we will send too the client side code.
$implodedFilesEqual=implode("|",$files);
//For testing purpose
print_r($files);
$toJson=json_encode($implodedFilesEqual);
echo ($implodedFilesEqual);
//Test.txt|test3.txt
}
?>
HTML page:
<html>
<head>
<title>Starting Page</title>
<link rel="stylesheet" href="StartPage.css" media="screen">
<script src="https://ajax.googleeapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="jQuery.js"></script>
</head>
<body id="theTextEditorsBody">
<p id="demo"></p>
<h1>Text Editor</h1>
<hr>
<textarea id="textArea"></textarea>
<br>
<select>
<option>textFile1</option>
<option>textFile2</option>
<option>textFile3</option>
</select>
<p id="hello"></p>
</body>
jQuery.js:
const xmlhttp=new XMLHttpRequest();
xmlhttp.onload=function(){
const myObj=JSON.parse(this.responseText);
document.getElementById("demo").innerHTML=myObj.name;
}
xmlhttp.open("POST","GettingFileInfo.php");
xmlhttp.send();

XMLHttpRequest() POST returns 405 error; method not allowed

My html code:
<h2>Please finalize your details</h2>
<form id="details" method="post" class="form">
Full name: <strong name="name_1">ABCDEF</strong><br><br>
ID No:<strong name="org_number_1">123</strong><br><br>
Mobile No:<strong name="ph_number_1"">1234567890</strong><br><br>
E-mail: <strong name="email_1">ABC#DEF.COM</strong><br><br>
ID Card: <img src="profile.png" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>
<button id="go">It's correct</button>
</form>
My javascript:
document.getElementById('go').addEventListener('click', submit);
function submit(){
var nme=document.getElementsByName("name_1")[0].innerHTML;
var id=document.getElementsByName("org_number_1")[0].innerHTML;
var phone=document.getElementsByName("ph_number_1")[0].innerHTML;
var email=document.getElementsByName("email_1")[0].innerHTML;
var img=document.getElementsByName("image")[0].src;
const xhr=new XMLHttpRequest();
xhr.onload=function(){
const serverResponse=document.getElementById("response");
serverResponse.innerHTML=this.responseText;
};
xhr.open("POST", "database_registration.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name="+nme+"&id="+id+"&phone="+phone+"&email="+email+"&img="+img); //this line throws the error "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)"
}
I am executing my code in Visual Studio Code editor and my project location is in:
C:\Users\Abhishek\Desktop\Web-dev stuff\XAMPP\htdocs\Stack hack 20 20
This is the error:
Not only that, I've also tried working with Fetch API, but it throws the same error too. What do I do now? How can I make it work?
The error is not in the JS it's come from the server. What is in database_registration.php? If that doesn't have handling for POST then I'd expect the server to return 405.
404 would mean database_registration.php isn't there, but 405 means it is there, but doesn't allow POST specifically. Check the allow header on the response for the methods that are supported.
Try:
xhr.open("GET", "database_registration.php?" +
"name="+nme+"&id="+id+"&phone="+phone+"&email="+email+"&img="+img);
xhr.send();
To make a GET request instead.
Alternatively this could be an error parsing the posted content (misreported, as it should be 400 or maybe 406), try removing parts of the body to see if it works with a subset.
I have done the first checkbox (ID No) for you.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cafteria details</title>
<style>
#special{
height: 100px;
width: 100px;
border: 1px solid;
display: none;
}
</style>
</head>
<body>
<h2>Cafeteria registration</h2>
<form class="details">
Full name: <input type="text" placeholder="Please avoid any kind of prefixes" id="name" size=25><br><br>
Organization:<div id="org"><input onclick="myFunction()" type="checkbox" id="cb1">ID no: <input type="number" id="org_number"><br><br>
<input type="checkbox" id="cb2">Mobile No: <input type="tel" id="ph_number"></div><br><br>
E-mail: <input type="email" id="email" size=25><br><br>
Upload ID Card: <input type="file" name="id" accept=".pdf,.jpeg" id="img"><br><br>
</form>
<div id ="special">
</div>
<button id="button">Register</button>
</body>
<script>
function myFunction() {
var x = document.getElementById("cb1").checked;
if (x == true) {
document.getElementById("special").style.display="block";
}else{
document.getElementById("special").style.display="none";
}
}
// var x = document.getElementById("cb1").checked;
// if (x==true){
// document.getElementById("special").style.display="block";
// console.log(true)
// }
// if (document.getElementById("cb2").checked==true){
// document.getElementById("special").style.display="block";
// console.log(false)
// }
</script>
</html>
Your code looks fine. If you are using Live Server vscode extension to run your code, this is a known issue (and here) with the extension.
You could try to change the port number settings on the Live Server extension as suggested in the link above but your best bet would be to stop using Live Server to run this code.
Just start XAMPP and navigate to the right url in your browser (note you will have to eliminate spaces in your project folder name to something like stack-hack-20-20).
EDIT: It also seems to be the case with some other vscode extensions. You get a 405 status when you try to reach an endpoint. There is some restriction to using GET, HEAD or OPTIONS http methods so you either hit the endpoint using one of those methods or use a webserver like XAMPP for POST, DELETE etc.
I agree with #Keith that this error code usually indicates that the request method you used is not allowed by the server, but I've seen that not all developers use the correct error codes in every case.
I suspect you may have a parsing issue on the backend for the data you're submitting, since it isn't being URI encoded before it's sent.
Try this JavaScript instead and see if you get a different result:
document.getElementById('go').addEventListener('click', submit);
function submit() {
const formData = new FormData();
formData.append("name", document.getElementsByName("name_1")[0].innerHTML);
formData.append("id", document.getElementsByName("org_number_1")[0].innerHTML);
formData.append("phone", document.getElementsByName("ph_number_1")[0].innerHTML);
formData.append("email", document.getElementsByName("email_1")[0].innerHTML);
formData.append("img", document.getElementsByName("image")[0].src);
const xhr = new XMLHttpRequest();
xhr.onload = function() {
const serverResponse = document.getElementById("response");
serverResponse.innerHTML = this.responseText;
};
xhr.open("POST", "database_registration.php");
xhr.send(formData);
}
Try to create new url endpoint that support POST request on your backend PHP application. So your HTTP request which is sent from javascript can use POST request.

Getting text from file using FileReader on Load

So, I've been working on a page that uses only local files (server is not an option, unfortunately. Not even a localhost. The struggle is real.) and I've come to a situation where I need to grab text from a .csv file and populate it to the page. I have this bit of code that works, but I need to have a file set within the function when a button is pressed. Looking up the file manually isn't an option (to visualize what I'm doing, I'm making a mock database file in the most annoying way possible (because I have to, not because I want to)).
In the page I would have something like:
<button id="myButton" onclick="getText()"></button>
<script>
var myFile = "dataset.csv";
...
</script>
The following bit of code works (in regards to having it pull the data from the csv file), but, as I said, I need to pull the text from the file when a button is pressed and just have the file name set in the script, not pulling it up manually.
<!DOCTYPE html>
<html>
<body>
<input type="file" id="fileinput" />
<div id="outputdiv"></div>
<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 splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
From what I can tell from the API, I would need to set the file attributes to a blob in order to pass it to FileReader. How I can do this without using an input box, I have no idea. There's also a 50% chance that I am completely wrong about this since I obviously don't know how to get this done.
If someone could show me how to achieve this with regards to what I'm looking for, it would be very much appreciated. I'm absolutely stumped.
Thank you.
Note: CORS restrictons will prevent this from working in most browsers. You can use FireFox Developer Edition, which disables CORS validation.
You can use an XMLHttpRequest to load a local file:
<!DOCTYPE html>
<html>
<body>
<button onclick="readSingleFile()">Click Me</button>
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile() {
let xhr = new XMLHttpRequest();
let url = "relative/path/to/file.txt;
if (!url) return;
xhr.onload = dataLoaded;
xhr.onerror = _ => "There was an error loading the file.";
xhr.overrideMimeType("text/plain");
xhr.open("GET",url);
xhr.send();
}
function dataLoaded(e){
var contents = e.target.responseText;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
</script>
</body>
</html>

php ajax javascript/ecmascript html write to text file

I'm not overly experienced with the aforementioned technologies, but need to resolve the issues i'm experiencing with the POST function.
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<meta charset='UTF-8'>
<script src='lib/ajaxget.js'></script>
<script src='lib/ajaxput.js'></script>
</head>
<body>
<h1>blah</h1>
<div>AJAX uploads go here.</div>
<div id="grabphpdiv"> AJAX uploads from PHP go here.</div>
<br>
<textarea id="comment" rows="5" cols="40"></textarea>
<br>
<button id="put">put</button>
<br>
<br>
<button id="get">get</button>
<script src='dyn.js'></script>
</body>
</html>
The JS 'GET' function is working, so here's the POST that doesn't work (no errors in the console) the text file doesn't update though...
function AjaxPut(URL, callback)
{ var ajaxObj = new XMLHttpRequest();
ajaxObj.open("POST", URL, true);
ajaxObj.onreadystatechange = function()
{ if (ajaxObj.status == 200)
if (ajaxObj.readyState == 4)
callback(ajaxObj.responseText);
};
ajaxObj.send("somestuff");
};
And the PHP for the post (though titled PUT here)
<?php
$jothandle = fopen("jots.txt","w");
fwrite($jothandle,$_REQUEST['line']);
Lastly, here's the JavaScript that's entitled 'dyn.js' at the bottom of the HTML. (though for brevity, i've only pasted in the POST section.
var y = document.getElementById("put");
y.addEventListener("click", runapi1);
y.addEventListener("click", grabphp1);
function runapi1()
{ AjaxPut('api/put.php', grabphp1);}
function grabphp1(response)
{ document.getElementById('grabphpdiv').innerHTML = response; }
Any help or pointers would be very much appreciated! thanks!
It looks like you aren't sending a parameter called line from your JS, but you are expecting one in your PHP code. Try sending this instead: line=somestuff e.g.
ajaxObj.send("line=somestuff");
Send POST data using XMLHttpRequest

Transfer data from one HTML file to another

I'm new to HTML and JavaScript, what I'm trying to do is from an HTML file I want to extract the things that set there and display it to another HTML file through JavaScript.
Here's what I've done so far to test it:
testing.html
<html>
<head>
<script language="javascript" type="text/javascript" src="asd.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
</html>
next.html
<head>
<script language="javascript" type="text/javascript" src="asd.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
<table>
<tr>
<td id="here">test</td>
</tr>
</table>
</form>
</body>
</html>
asd.js
function testJS()
{
var b = document.getElementById('name').value
document.getElementById('here').innerHTML = b;
}
test.html -> ads.js(will extract value from the test.html and set to next.html) -> next.html
Try this code:
In testing.html
function testJS() {
var b = document.getElementById('name').value,
url = 'http://path_to_your_html_files/next.html?name=' + encodeURIComponent(b);
document.location.href = url;
}
And in next.html:
window.onload = function () {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.name;
}
Description: javascript can't share data between different pages, and we must to use some solutions, e.g. URL get params (in my code i used this way), cookies, localStorage, etc.
Store the name parameter in URL (?name=...) and in next.html parse URL and get all params from prev page.
PS. i'm an non-native english speaker, will you please correct my message, if necessary
The old fashioned way of setting a global variable that persist between pages is to set the data in a Cookie. The modern way is to use Local Storage, which has a good browser support (IE8+, Firefox 3.5+, Chrome 4+, Android 2+, iPhone 2+). Using localStorage is as easy as using an array:
localStorage["key"] = value;
... in another page ...
value = localStorage["key"];
You can also attach event handlers to listen for changes, though the event API is slightly different between browsers. More on the topic.
Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.
Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:
Session Cookies
HTML5 LocalStorage
POST the variable in the url and retrieve them in next.html via window object
With the Javascript localStorage class, you can use the default local storage of your browser to save (key,value) pairs and then retrieve these values on whichever page you need using the key.
Example -
Pageone.html -
<script>
localStorage.setItem("firstname", "Smith");
</script>
Pagetwo.html -
<script>
var name=localStorage.getItem("firstname");
</script>
I use this to set Profile image on each page.
On first page set value as:
localStorage.setItem("imageurl", "ur image url");
or on second page get value as :
var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);
you can simply send the data using window.location.href first store the value to send from testing.html in the script tag, variable say
<script>
var data = value_to_send
window.loaction.href="next.htm?data="+data
</script>
this is sending through a get request
HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed
document.getElementById('here').innerHTML = data.name;
This needed to be changed to
document.getElementById('here').innerHTML = data.n;
I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .
<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>
<body>
<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
client side scripting
function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}
jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.
jquery load function http://api.jquery.com/load/
The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.
1) page1.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 1 - Codemaker</title>
</head>
<body>
<form method="get" action="page2.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=text name=age size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
2) page2.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 2 - Codemaker</title>
</head>
<body>
<script>
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</body>
</html>
I coded the answers from Alex Fitiskin, and added a bit of extra code.
I added a parameter to the onLoad function to get the form's submit event, and prevent it's default behaviour first.
Here's the code:
test.html
<html>
<head>
<script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get" onsubmit="return testJS(event)">
name:<input type="text" id="name" name="n">
<input type="submit" value="next">
<!-- <button type="button" id="print" onClick="testJS()"> Print </button> //Button not needed anymore -->
</form>
</body>
</html>
next.html
<head>
<script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
<table>
<tr>
<td id="here">test</td>
</tr>
</table>
</form>
</body>
</html>
test.js
function testJS(e) {
e.preventDefault();
var b = document.getElementById('name').value,
url = 'http://path_to_next_location/next.html?name=' + encodeURIComponent(b);
document.location.href = url;
}
function onLoad() {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {},
tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.name;
}
window.onload = onLoad;
This way the onload function will be replaced with the custom onLoad function, and the form will not be submitted the default way, but instead using the code inside the testJS function.
Avoid localstorage use as data are not safe with get method. Best option is to use script set to module and then export & import data via 2 js files to html file. Variable value can be passed between pages using module method.

Categories