I am trying to read in lines from a text file that are in this form;
34.925,150.977
35.012,151.034
34.887,150.905
I am currently trying to use this methodology, which obviously isn't working. Any help would be appreciated.
var ltlng = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "C:\Gmap\LatLong\Coordinates.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) { // Makes sure it's found the file.
lines = txtFile.responseText.split("\n"); // separate each line into an array
ltlng.push(new google.maps.LatLng(lines.split(",")[0],lines.split(",")[1]); //create the marker icons latlong array
}
}
}
XMLHttpRequest works when resources are called by HTTP/S protocol (and not file protocol, as in your example)
So to make your code work, you should try this code along with a web server
Related
So, I am making a simple little program for work that retrieves a current sheet from google sheets using the following javascript
const key = ("KEY");
const SHEETID =("SHEET");
setInterval(function(){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
addRow("orders",xmlHttp.responseText);
},5000);
}
xmlHttp.open("GET","https://sheets.googleapis.com/v4/spreadsheets/SHEETID/values/Sheet1/?key="+key, true); // true for asynchronous
xmlHttp.send(null)
function addRow(tbl_nme,responseText){
console.log(responseText)
var obj = JSON.parse(responseText);
setInterval(function(){
getrowI(tbl_nme,obj)
},5000);
}
This part works fine and I can render this into a html5 table with a button on it.
However when I go to post a command to remove a row from a google spreadsheet using the clear API, I get a 401 error and I can't figure out what I am doing
wrong.
the POST code i use looks like this:
function postoff(cel){
console.log(cel);
var posturl = ("https://sheets.googleapis.com/v4/spreadsheets/SHEETID/values/"+"!A"+cel+":"+"F"+cel+":clear"+"?key="+key);
axios.post(posturl);
}
according to https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/clear
My format should be close, but not sure what I am doing wrong. Anyone have an idea?
(I found some similar questions but none of them solved my problem so this is not a duplicated question I think)
I want to retrieve filenames in one of my folder using jQuery. I tried the following method but I still can't get each filename.
$.get(".", function(data) {
$("#divID").append(data);
});
But I noticed that the type of 'data' is string and it contains filenames at the end of it like this:
<script>addRow("filename.csv","filename.csv",0,238618,"233 kB",1512119177,"12/1/17, 5:06:17 PM");</script>
So is there anyway I can retrieve the filenames from 'data'? (not by using regex)
You cannot read files in a client's machine. You may access them for development purpose by modifying a flag. Look at my answer here regarding this. After this proceed with the below code.
Both works.
Using PURE JAVASCRIPT :
var filenames=[], foldernames=[];
var url = "file:///Users/Default/Downloads";
var req = new XMLHttpRequest();
req.open("GET",url,true);
req.onreadystatechange=function(){
if(req.readyState === 4)
{
document.write(req.responseText);
getNames();
}
};
req.send();
function getNames()
{
var files = document.querySelectorAll("a.icon.file");
var folders = document.querySelectorAll("a.icon.dir");
files.forEach(function(item){filenames.push(item.textContent)})
folders.forEach(function(item){foldernames.push(item.textContent.slice(0,-1))})
console.log(filenames);
console.log(foldernames);
}
Using JQUERY :
var filenames=[], foldernames=[];
$.get("file:///Users/Default/Downloads",function(response){
document.write(response);
getNames();
});
function getNames()
{
var files = document.querySelectorAll("a.icon.file");
var folders = document.querySelectorAll("a.icon.dir");
files.forEach(function(item){filenames.push(item.textContent)})
folders.forEach(function(item){foldernames.push(item.textContent.slice(0,-1))})
console.log(filenames);
console.log(foldernames);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am very new to coding and javascript; just a few days in. I was wondering if there was a way to import objects from a text file(separated by lines) to use in my array: replyText. Here is what I'm working with:
// Variables
var theButton = document.getElementById("theButton");
var mainText = document.getElementById("mainText");
var replyText = [...,...,...,...,];
var i = 0;
// Functions
function nextText() {
mainText.innerHTML = replyText[i++ % replyText.length];
}
// MAIN SCRIPT
theButton.onclick = function() {
nextText();
};
You can use XMLHttpRequest to get the .txt file just pass the path of it.
var file = new XMLHttpRequest();
file.open("GET", "file:/../file.txt", false);
file.onreadystatechange = function () {
if (file.readyState === 4) {
if (file.status === 200 || file.status == 0) {
var text = file.responseText;
alert(text);
}
}
}
EDIT: you must pass the absolute path file:///C:/your/path/to/file.txt
For client/browser-side file reading:
You cannot easily read a file on the client-side as you are not allowed direct access to the client's file system. However, you can place a input element of file type in your HTML markup via which the client can load a file for your program to process. For example:
<input type="file" id="file" onchange="readFile()" />
Now when the client selects a file for use, the readFile() function will be called which will read and process the file. Here's an example:
function readFile() {
var file = document.getElementById('file').files[0]; // select the input element from the DOM
var fileReader = new FileReader(); // initialize a new File Reader object
fileReader.onload(function() { // call this function when file is loaded
console.log(this.result); // <--- You can access the file data from this variable
// Do necessary processing on the file
});
fileReader.readAsText(file); // Read the file as text
}
For more information on File Reader, check out the docs.
To add on to Paulo's solution, read below for splitting string by line breaks (new line character)
var replyText = text.split("\n"); // "\n" is new line character
I'm trying to do something fairly simple I think but I'm missing something. I've very new to Javascript. I'm trying to read a CSV file in to an array (in my code below I'm simply trying to output the data to an alert box). I keep getting an error "access denied."
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
I suspect there is an issue with where I have the csv file located? Due to restrictions with our CMS I can only reference the file like this www.example.com/csvfile.csv.
Any help would be greatly appreciated.
Here is sample code for reading csv file into array
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
var csvData = new Array();
var jsonObject = request.responseText.split(/\r?\n|\r/);
for (var i = 0; i < jsonObject.length; i++) {
csvData.push(jsonObject[i].split(','));
}
// Retrived data from csv file content
console.log(csvData);
Here is the working fiddle example: http://jsfiddle.net/BdCnm/450/
Give this link a try and check his source code on Github, he lays it out in a pretty concise way.
https://github.com/MounirMesselmeni/html-fileapi
I would like to display the variable "hashrate" from this JSON file on a HTML webpage. I have looked around the internet, but many of the methods have not worked. Sorry if this is a duplicate question, I am very lost.
var json = {"getpoolstatus":{"version":"1.0.0","runtime":19.948959350586,"data":{"pool_name":"Capy's Pool - Gabencoin","hashrate":5.8254222222222,"efficiency":0,"workers":0,"currentnetworkblock":21903,"nextnetworkblock":21904,"lastblock":21903,"networkdiff":0.0392466,"esttime":28935.733248,"estshares":2572,"timesincelast":189,"nethashrate":451133}}};
your variable - json.getpoolstatus.data.hashrate
var xhr = new XMLHttpRequest(); //Request the data
xhr.open('POST','http://gaben.capyspool.co.uk/gabencoin/public/index.php?page=api&action=getpoolstatus&api_key=72f3fd60d9a536215a6f6f92938592a60f919586635d7d0dedcf6a394888c435',true);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState === 4) { //When it's ready
var data = JSON.parse(this.responseText); //Parse the data
alert(data.getpoolstatus.data.hashrate); //And here it is!
}
}