How can I read and print out a plain text file on my server line by line in reverse using javascript? I would prefer to use javascript or jquery over php but have no idea how to accomplish something like this. So for instance if I had a file like
foo
bar
foobar
barfoo
I would like it to print out
barfoo
foobar
bar
foo
Using a http-Request:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
var content = httpGet("google.de"); //enter the Url of your text file here
var lines = content.split("\n");
var result = "";
for(var i=0; i<lines.length; i++)
result = lines[i] + "\n" + result;
alert(result);
Demo is here (displaying the source of http://google.de backwards)
You can do it using the FileReader API. I am not sure if its still in draft or not, but it works in Chrome as well as Firefox.
You will have to simply read the file as text using readAsText method. And then split() the string based on \n and then reverse() and join() again.
Here is a jsFiddle example.
Related
I need to console.log this value:
the
Specifically location which is under geometry
right now I able to print this entire set of data with this javascript code:
var url='https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=APIKEYHERE';
function Get(url){
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET", url, false);
Httpreq.send(null);
return Httpreq.responseText;
}
var json_obj = JSON.parse(Get(url));
console.log(json_obj.results);
This code will not work for anyone who is trying to live test because you need an API Key.
The problem that I run into is that when I try and
console.log(json_obj.results.0)
I get this error:
Does anyone know how to print this value?
To access ith element of an array:
results[i];
So you should use:
console.log(json_obj.results[0]);
Try this: (untested)
console.log(json_obj.results[0].geometry.location)
I am trying to parse text from a dictionary.txt file for a web browser word game. I found How to read a local text file? and used the readTextFile(file) function the top commentor suggested. However, I don't understand how to get the parsed text into a set.
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;
alert(allText)
}
}
}
rawFile.send(null);
}
alert(allText) gives me a popup with words in the dictionary.txt, so I know the words are getting properly parsed into the variable allText.
How do I now move these words into a set structure for use in my game? I am thinking I would do this in my main program--run readTextFile, then move to set.
Also, as this is my first time using JavaScript, when I run readTextFile in my main program, do I need to do:
myWords = readTextFile("dictionary.txt");
To store allText intomyWords, or will simply doing:
readTextFile("dictionary.txt");
Make it so that I can access allText in my main program? I am unfamiliar with scoping in JS.
I think that all you will need to do is split the text file by new-lines and send the resulting list and instantiate a new Set object with the mentioned list.
Also, check out the documentation on MDN for the Set object.
let myWords = readTextFile("dictionary.txt");
console.log(myWords.has('apple')); // true
console.log(myWords.has('banana')); // true
console.log(myWords.has('carrot')); // true
console.log(myWords.has('durian')); // false
function readTextFile(filename) {
// Blah, blah, blah...
// Code to read the file and return a string...
// Ok, now we have a result:
let result =
`apple
banana
carrot
`;
return new Set(result.split('\n')); // Split the text by new-line and instantiate
}
We will need to know the format of the file to help you parse it. If it is a text file with a word on each line, then you could return allText; in your function, then put it into an array using
var myWords=readTextFile('dictionary.txt').split("\n");
I've searched and searched and quadruple checked spelling and syntax and I'm stumped. I even checked the syntax on "jslint". I've placed all the code on "jsfiddle":
http://jsfiddle.net/sxtuX/
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function process() {
if (xmlHttp) {
try{
xmlHttp.open("GET", "data_people.xml", true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.send(null);
}
catch (e) {
alert ("In process function.<br/>Error in creating xmlHttp object: "+ e.toString());
}
}
}
function handleStateChange() {
if(xmlHttp.readyState==4) {
if (xmlHttp.status==200) {
try {
handleResponse();
}
catch(e) {
alert ("Trouble getting text." + e.toString());
}
}
else {
alert ("State = "+xmlHttp.readyState+" Status= " + xmlHttp.status);
}
}
}
function handleResponse() {
var xmlResponse = xmlHttp.responseXML,
root = xmlResponse.documentElement,
names = root.getElementsByTagName("name"),
ssns = root.getElementsByTagName("ssn");
alert (xmlHttp.responseText);
var stuff = "";
for(var i=0;i<names.length;i++) {
stuff = names.item(i).firstChild.data + "-" + ssns.item(i).firstChild.data + "<br/>";
}
theD = document.getElementById("theD");
theD.innerHTML = stuff;
}
The javascript works fine up until the last function "handleResponse()" which is the last function. I've placed an "alert" after all the variable declarations using "xmlHttp.responseText" just to prove to myself the file is being accessed and it does print the entire XML file in the alert window.
I tried to create the XML datafile on "jsfiddle" by following the instructions, assuming it was like the HTML file example, but I couldn't get it to work.
So my questions: Why isn't "xmlHttp.responseXML" returning anything? It's either that or something is going wrong with .documentElement. When I examine "names.length" or "ssns.length" they are both zero. Also, can I get some assistance in figuring out the proper way to code an XML file on "jdfiddle" by correcting my fibble attempt?
The way you have your javascript options in the fiddle are set up it only gets executed onLoad (which means all your functions will be defined inside an onload function - and will both not be available in the global scope nor before said function has been executed). It's a catch 22 with sprinkles on top. You'll need to set the second dropdown on the left to either No wrap - in <head> or No wrap - in <body>.
Next up - the jsfiddle example code. There's a whole bunch wrong here:
You should have been referencing Request - not Request.XML (which you just made up ;P). And you should have included the MooTools library (first dropdown on the left) - because that's where Request is from ;)
The url is case sensitive! "/echo/xml/" instead of "/echo/XML/".
The xml string needs to be have properly escaped quotes and javascript strings don't support raw line-breaks (they can be escaped too... but that's another story) - just collapse them for now.
... But you don't need that example. Just use your own code!
Just remember to use the proper test url (with POST not GET) and escape/collapse your test xml.
This is a working fiddle: http://jsfiddle.net/sxtuX/3/
I am building a photo slider in JavaScript and jQuery. It works perfectly in chrome, but not in IE6 where I know most of my clients would view it.
I have this function:
function getFacebookPhotos(photoCount, pageId) {
var picsUrl = "http://api.facebook.com/method/fql.query?query=SELECT%20src_big,%20src_big_height,%20src_big_width%20FROM%20photo%20WHERE%20pid%20IN%20(SELECT%20pid%20FROM%20photo_tag%20WHERE%20subject='243117879034102')%20OR%20pid%20IN%20(SELECT%20pid%20FROM%20photo%20WHERE%20aid%20IN%20(SELECT%20aid%20FROM%20album%20WHERE%20owner='" + pageId + "'%20AND%20type!='profile'))";
var responseText = $.ajax({
url: picsUrl,
async: false,
dataType: "xml",
success: function(text) {
responseText = text;
}
}).responseText;
var xmlDoc = $.parseXML(responseText);
var $xml = $(xmlDoc);
var $photos = $xml.find("photo");
var resultantPhotos = [];
for (var i = 0; i < photoCount; i++)
{
var $element = $($photos[i]);
var $src_big = $element.find("src_big");
var $text = $src_big.text();
resultantPhotos.push($text);
}
return resultantPhotos;
}
It fetches the XML response from a facebook query, parses it, and returns an array of photo urls from a facebook page. In Chrome, this works, but in Internet Explorer 6, the returned photo array is null. In both browsers the code executes without error.
I was using this JavaScript to parse the XML:
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("GET", picsUrl, false); // Throws permission error in IE
xmlHttp.send(null);
var photos;
if (window.DOMParser)
{
var parser = new DOMParser();
xml = parser.parseFromString(responseText, "text/xml");
}
else // Internet Explorer
{
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(responseText);
}
photos = xml.getElementsByTagName("photo");
But that gave me errors in IE while still working in Chrome so I switched to jQuery.
Do you know what's wrong with it?
This may or may not be accurate, but I think the solution is to not use javascript at all, but to use PHP instead.
My errors were caused by javascript's lack of permission to access remote files. When I tried retrieving the XML output first with this PHP code:
<?php file_put_contents("query.xml", file_get_contents($facebookPicsUrl)); ?>
My javascript code
xml.open("GET","query.xml",false);
worked perfectly, but it made me realize that I should be using PHP, not only because downloading an xml file to my server is clunky, but because PHP can do everything that my JS is doing with simplexml_load_file. Everywhere I went looking for "how to get IE to open remote XML," they flat out say "you can't." Regardless of whether or not it's possible, it will be much easier to do this in PHP.
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