I've been trying to learn how to read a text file locally using JavaScript and Ajax. I've been looking on some tutorials online, and have followed them, but no matter what I do I cannot get my text to display what is in the .txt file.
function loadDoc(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
xmlhttp.open("GET","names.txt",true);
allText = xmlhttp.responseText;
lines = xmlhttp.responseText.split("\n");
}
}
xmlhttp.send(null);
document.getElementById("myDiv").innerHTML=allText;
}
I think this is meant to change the div I have (id "myDiv") to read what is in the text file, but it does not seem to do this, no matter what I try. Any help would be appreciated - I'm still new to JavaScript and Ajax.
Use Firebug or Chrome's developer tools to make sure that the AJAX call is returning the correct text.
Is names.txt in the same directory as the HTML page?
Related
The situation is, that I want to use "runScript" in order to send a xmlhttprequest in the beginning when the website gets opened, find an element in the responseText, see if a specific textcontent is present and if so, I want to click on that element.
I am not allowed to show you the source of the website, but I hope your still able to (maybe) find the mistake.
My script:
javascript{
var req = new XMLHttpRequest();
req.addEventListener("load", function(event) {
if(req.status >= 200 && req.status < 300)
{
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(req.responseText, "text/html");
if(document.getElementById("application_widgets__0_selectedUserLanguage_label").childNodes[0].textContent=="English")
{
document.getElementById("application_widgets__0_selectedUserLanguage_label").parentNode.click()
}
}
});
req.open("GET", "..............................");
req.send();
}
I've already tested it in the console of firebug before putting it into the Selenium IDE and it works perfectly. But I always get the same exception when running it in Selenium IDE:
My question is: why does it work in firebug but not in selenium IDE and what did I do wrong?
no there's no iframe
Thanks for the answers in advance! :)
This indicates that the page is not fully loaded yet when you call document.getElementById(). You need to wrap your code in a window.addEventListener("load", function() { ... }); to get it to work.
I have a php script (just for calculation) and a html file. Let's say the php file has finished its calculation and the solution is 10. The following line is in the body of the just mentioned html file:
<div id="here"></div>
Now I want the php file to write the 10 into the html. I thought of adding a few lines of javascript at the end of the php to make the job. The question is if this is even possible with something like (index.html).getElementById(here).innerHTML or something. Both files are in the same folder and setting the proper permission shouldn't be a problem.
I know I could put everything in one file but this is part of a bigger project. I just adapted my problem on this simple example to avoid that you need to read plenty of lines.
Your Script should look like this to get response from PHP
<script>
function loadDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("here").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "yourphp.php?q=" + str, true);
xmlhttp.send();
}
</script>
Hope this solves your problem
ref: http://www.w3schools.com/ajax/ajax_php.asp
PHP is server-side and Javascript is client-side. I don't recommend you to use embedded PHP but you should take a look at Ajax Requests.
Here's some documentation
I am trying to get text from a service on the same server as my webserver. The link is something like this:
http://<OwnIPadres>:8080/calc/something?var=that
This is my code:
function httpGet(theUrl)
{
alert(theUrl);
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
alert("text: " + doc.responseText );
document.getElementById('ctm').text = doc.responseText;
}
}
doc.open("get", theUrl);
doc.setRequestHeader("Content-Encoding", "UTF-8");
doc.send();
}
The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?
Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.
I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an
Access-Control-Allow-Origin: http://:8080/
in your header (however that will only get you the most modern browsers).
Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.
I am trying to learn how to read into a web page data in an XML file. This is a static HTML page. I do not want a web server and I cannot use Ajax. The XML file is local (in the same directory as the HTML file). I want this to work in a Chrome browser.
What I need to do is:
Read the XML file on the page onLoad event.
Use innerHTML to insert the XML data into a div.
My problem is in reading the XML file. All of the examples I have found I think will only work if there is a web server running, which I have to avoid.
If you're reading another file the only way to do that with front end JS is another request (ajax). If this were node.js it would be different because node can access the filesystem. Alternatively if you get the xml into a javascript string on the same page, you can manipulate it. There are a number of good libraries (jquery's parseXML).
Original answer here: https://stackoverflow.com/a/48633464/8612509
So, I might be a little late to the party, but this is to help anybody else who's been ripping his/her hair out looking for a solution to this.
First of all, CORS needs to be allowed in the browser if you're not running your HTML file off a server. Second, I found that the code snippets most people refer to in these kind of threads don't work for loading local XML-files. Try this (example taken from the official docs):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', true);
xhr.timeout = 2000; // time in milliseconds
xhr.onload = function () {
// Request finished. Do processing here.
var xmlDoc = this.responseXML; // <- Here's your XML file
};
xhr.ontimeout = function (e) {
// XMLHttpRequest timed out. Do something here.
};
xhr.send(null);
The method (1st arg) is ignored in xhr.open if you're referring to a local file, and async (3rd arg) is true by default, so you really just need to point to your file and then parse the result! =)
Good luck!
Since you're only targeting Chrome, you could take a look at the File API. You'd have to prompt the user to select the file or drop it into a specific area of the page though, which might be something you'd rather avoid, or not. The following HTML5 Rocks article should help.
Assuming the HTML, XML and browser are all on the same machine, you might try using an Iframe in the HTML that references the XML using a URL like file:\.
You could do something like this:
<html>
<head>
<script type="text/javascript">
//If using jQuery, select the tag using something like this to manipulate
//the look of the xml tags and stuff.
$('#xframe').attr('style', 'thisxmltag.....');
</script>
</head>
<body>
...
<frame id="xframe" src="the_xml_doc"></src>
</body>
</html>
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", file_Location, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById(your_div_id).value =
xmlDoc.getElementsByTagName(The_tag_in_xml_you_want_to_display)
[0].childNodes[0].nodeValue;
Works with IE11
<head>
// To be hidden with a better method than using width and height
<OBJECT id="data1" data="data.xml" width="1px" height="1px"></OBJECT>
// to work offline
<script src="lib/jquery-2.2.3.min.js"></script>
</head>
<body>
<script>
var TheDocument = document.getElementById("data1").contentDocument;
var Customers = TheDocument.getElementsByTagName("myListofCustomers");
var val1 = Customers[0].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
i tried a lot for this, but didnt find the answer . How can i read a file using javascript or html . I have a text file "sample.txt" and i have some information in it . It is placed in the same folder as the html file is placed where the html file contains the html code that deals with this file . I just want to read the information from the file and display it on some div or whatever, i mainly want to know how to read a file .
Will provide more information if necessary .
Thanks
At first: JavaScript is executed on client-side. Though you have to put up an AJAX-Request to fetch the content of your file. I think jQuery's load() seems to be the easiest way to achieve this.
For example:
$('#theContentElement').load('sample.txt');
You can do a regular Ajax request without jQuery aswell to read a file.
Following uses a GET request to get data from myfile.txt and outputs it to the DIV-tag with id output.
<script>
function ajaxGet()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("output").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","myfile.txt",true);
xmlhttp.send();
}
ajaxGet();
</script>
<div id="output"></div>
You may fetch the actual file content using javascript. Here is a sample code using jquery using the load function:
$("#YOUR_DIV_ID").load("sample.txt");
This will update the content of the div with the id YOUR_DIV_ID with the content of "sample.txt"