Getting a remote CSV file and putting it into a variable - javascript

I have a simple javascript script, and I want to use a CSV file present in a remote url (for instance https://not-my-domain.com/test.csv) in it.
I don't need to parse the CSV, just to get it as a simple string. I've tried:
function getCSV() {
var file = "https://not-my-domain.com/test.csv";
var rawFile = new XMLHttpRequest();
var allText;
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4)
if(rawFile.status === 200 || rawFile.status == 0)
allText = rawFile.responseText;
};
rawFile.send();
alert(allText); //UNDEFINED!
return allText;
}
But somehow the allText is still undefined after the function has terminated. If you could assist me in this little issue I'd be glad.

use a lambda for an easy callback. You'll need a proxy to fetch the remote domain csv, or be sure it has cors enabled.
function getCSV(func) {
var file = "https://not-my-domain.com/test.csv";
var rawFile = new XMLHttpRequest();
var allText;
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4)
if(rawFile.status === 200 || rawFile.status == 0)
allText = rawFile.responseText;
if(func!=undefined && typeof(func) == "function"){
func(allText);
}
};
rawFile.send();
}
getCSV(function(contents){
alert(contents);
})

Related

replacing HTML text with date from text file

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);

Get the txt file into the push() method?

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);
};

Store each line of text file into an array and remove \n

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'));
}

Having trouble making a XMLHttpRequest()

I am trying to make an XMLHttpRequest, however, I am having issues. The page keeps refreshing automatically even when returning false or using e.preventDefault(). I'm trying to get cities to eventually pass through an options block. (I've started the option section and will complete it after I figure out the get request issue.) I'm trying to do this using pure Javascript because I've already done it using Angular and Node. Any help would be appreciated.
HTML:
<form id="citySearchForm" method="get" onSubmit="return searchFormFunc();">
<div>
<p>Choose a city:</p>
<input type="text" placeholder="Enter a city" id="getCitiesInput" name="city">
<input type="submit" value="submit">
</div>
<div id="weather"></div
<p><span id="temp"></span></p
<p><span id="wind"></span></p>
</form>
Javascript:
var citySearch = document.getElementById("citySearchForm");
// citySearch.addEventListener("submit", searchFormFunc);
function searchFormFunc(e){
cityName = document.getElementById('getCitiesInput').value;
var searchCityLink = "http://autocomplete.wunderground.com/aq?query=";
var search = searchCityLink.concat(cityName);
console.log("link : " + search);
var xhr = XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText
console.log(r);
} else {
console.log('error');
}
};
xhr.open("GET", link, true);
xhr.send(null);
var r = JSON.parse(xhr.response);
return false;
// e.preventDefault();
}
You are specifying that you want this to be an async request. So you need to parse your response inside of the onreadystatechange or onload.
function ajax(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
/** Here you can specify what should be done **/
xhr.onreadystatechange = function() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Answer from documentation by user6123921
You have to use var xhr = new XMLHttpRequest();
you have to define an onreadystatechange event listener
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText
console.log(r);
/* do stuff with response */
}
};

Csv file to an array

I have a csv file which contains the following values:
18/10/2013, news item 1
18/10/2013, news item 2
17/10/2013, news item 3
16/10/2013, news item 4
How do I go about putting this into an array in JavaScript, ordered by date?
Once I have got it into an array, I also need to get the text values.
So far I have something like this:
Function readTextFile(){
var rawFile = new XMLhttpRequest();
Var myArray;
rawFile.open("GET", csvfile, true);
rawFile.onreadystatechange = function(){
if(rawFile.readyState === 4){
if(rawFile.Status === 200 || rawFile.Status === 0)
{
}
}
}
Sorry if the text above is not formatted properly, I am posting from my phone. thanks
This is how you can do it.
Function readTextFile(){
var rawFile = new XMLhttpRequest();
Var myArray;
rawFile.open("GET", csvfile, true);
rawFile.onreadystatechange = function(){
if(rawFile.readyState === 4){
if(rawFile.Status === 200 || rawFile.Status === 0)
{
var response = rawFile.responseText;
var splitData = new Array();
//split data with new line
splitData = response.split("\n"); //stores all the values separated by new line
console.log(splitData[0]); //returns 18/10/2013, news item 1
//split single line data with comma
var splitComma = new Array();
var splitComma = splitData[0].split(",");
console.log(splitComma[0]); //returns 18/10/2013
//start comparing date values here
}
}
}
var myArray = rawFile.responseText.split(",");
But it will not sort the data according to login date

Categories