Setting a javascript variable to an external markdown file - javascript

I have a long markdown file. I also have a javascript file that runs a parser over markdown. In my javascript file I have set:
var text = "md/markdown.md"
This does not seem to pull in the content of the markdown file as I would like it to. However, if I copy and paste the contents of the markdown file into the variable, then everything works as it should. Is there a way I can set this javascript variable to pick up the contents of this external markdown file?

In the context of a web browser, if you want JavaScript to fetch data from a URI then you will generally use the XMLHttpRequest object. MDN has a decent tutorial about using XMLHttpRequest.
Most of the general purpose JavaScript libraries include wrappers for XHR that include compatibility fixes (especially for old-IE). I'm fond of YUI. Another option is the relatively ubiquitous jQuery.
It isn't a problem for the case given in the question, but beware of the same origin policy.

Run an AJAX request:
var ajaxRequest, text;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
text = ajaxRequest.responseText;
}
}

Javascript cannot directly read local files for security reason. As an alternative way, you can take use of XMLHttpRequest to achieve it. Please check the link on the stackoverflow: read external file with Javascript. In addition, HTML5 provides a standard way to interact with local files, via the File API specification. You may refer to the tutorial: http://www.html5rocks.com/en/tutorials/file/filesystem/

Related

Read XML File using Javascript from a Local Folder

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;

reading server file with javascript

I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:
<IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>
and (with file_inhoud, lines defined elsewhere)
function readFile() {
func="readFile=";
debug2("0");
var x=document.getElementById("myframe");
debug2("1");
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2("1a"+doc);
var file_inhoud=doc.document.body;
debug2("2:");
lines = file_inhoud.split("\n");
debug2("3");
fileloaded();
debug2("4");
}
Debug function shows:
readFile=0//readFile=1//readFile=1a[object HTMLDocument]//
So statement that stops the program is:
var file_inhoud=doc.document.body;
What is wrong? What is correct (or best) way to read this file?
Note: I see that the file is read and displayed in the frame.
Thanks!
Your best bet, since the file is on your server is to retrieve it via "ajax". This stands for Asynchronous JavaScript And XML, but the XML part is completely optional, it can be used with all sorts of content types (including plain text). (For that matter, the asynchronous part is optional as well, but it's best to stick with that.)
Here's a basic example of requesting text file data using ajax:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
You'd call that like this:
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
However, the above is somewhat simplified. It would work with modern browsers, but not some older ones, where you have to work around some issues.
Update: You said in a comment below that you're using jQuery. If so, you can use its ajax function and get the benefit of jQuery's workarounds for some browser inconsistencies:
$.ajax({
type: "GET",
url: "path/to/file",
success: function(text) {
// `text` is the file text
},
error: function() {
// An error occurred
}
});
Side note:
I found that javascript is client based...
No. This is a myth. JavaScript is just a programming language. It can be used in browsers, on servers, on your workstation, etc. In fact, JavaScript was originally developed for server-side use.
These days, the most common use (and your use-case) is indeed in web browsers, client-side, but JavaScript is not limited to the client in the general case. And it's having a major resurgence on the server and elsewhere, in fact.
The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();
The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.

SQL query using AJAX in Wordpress theme

I'm attempting to use AJAX to insert data into a database, but am unable to connect to the .php file on the server end. I'm thinking this is due to the fact that this is all run on Wordpress, so my normal url path to the .php file might not be correct.
Here is my setup:
Template file:
$('#newsletter-register').submit(function(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
}
}
ajaxRequest.open("GET", "register_newsletter.php", true);
ajaxRequest.send(null);
});
'#newsletter-register' is form that the user will use to submit his/her information. The alert when the ajaxRequest is at readyState 4 is thrown correctly, but will an empty value.
My php is a simple echo returning a string to signal that the connection is correct (presently I'm just trying to see if the files are correctly calling eachother).
I'm thinking it must be the url path to register_newsletter.php as I've tried placing the code within the template file, outside, etc.
My javascript file is located in /theme/assets/js/code.js where as my template files (including the register_newsletter.php file) in /theme.
Any ideas?
I had this type of issue yesterday. In my situation the page would only be accessed from
www.site.com/aFolder/
The script was stored in my
'/wp-content/themes/themeName/processForm.php'
folder.
and the URL I used was:
../wp-content/themes/themeName/processForm.php
My JS was simply in the head of the main header.php file, but note that the URL I had to use was relative to the URL the page the script was accessed from.
Does that shed any light on things?
EDIT:
As troubleshooting steps, try ensuring you can access your php file from it's absolute URL, and have a look in firebug to see what link is being called when you fire the ajax request to see if it matches up with what you expect.

Javascript XML reading problem

I'm having problems reading an XML local input. The weird thing is that this code works perfectly when the XML is located on a server(This is desktop, by the way, so no SOP problems). I can't figure this out for the life of me, and I've been staring at it, trying different things for a couple of hours.
And another question: does the XML document need a css sheet to be properly read? I would imagine that it doesn't, but I don't know too much about it.
function verify()
{
zipObj = new ActiveXObject("Msxml2.XMLHTTP");
zipObj.open("GET", "KMSY.xml", false);
zipObj.onreadystatechange = function() {
if (zipObj.readyState === 4) {
zipXML = zipObj.responseXML;
read(zipXML);
}
else {
document.getElementById("notice").innerHTML = zipObj.readyState;
}
}
zipObj.send();
}
function read(zipXML)
{
var temp = zipXML.getElementsByTagName("temp_f")[0].childNodes[0].nodeValue;
document.getElementById("notice").innerHTML = temp;
}
Import the XML file to a local server, AJAX obviously needs the XML files to be on web server in order to parse them, or so my humble experience tells me.
You might also want to add the compatibility code for other XML requests into your code.
new XMLHttpRequest() for all browser and IE 8+
new ActiveXObject("Microsoft.XMLHTTP") IE prior to 8

Can someone help me understand AJAX (JSON) problem?

My goal is to create an personal application out of my ActionScript3 video player. I want to be able to hold keep the single .swf file in my browser and through AJAX, pass the .swf the url to my videos. I've chosen to use JSON as my data.
I'm new to JSON and I've hit a wall. It seems completely easy, but at first I wasn't even able to even get my locally hosted .json file into my webapp. It was working when I tried to do this with XML. After a bunch of trouble shooting, it is now in fact getting my XMLHttpRequest.
I'm trying to keep with backwards compatibility as much as possible, and thus I'm using the json2.js library to secure that notion.
My current issue is not being able to parse my XMLHTTPRequest. To be honest, I'm not even sure if what I'm doing is right as everywhere I look for examples, they're almost all pointing to a solution that writes the JSON into the actual webpage.
My external JSON file: test.json.
{ "video":"test.f4v", "thumb":"test.jpg", "title":"The test", "caption":"TEST TEST TEST TEST TEST", "minutes":01, "seconds":43 }
I'm positive the JSON file is valid.
Here is my html/javascript:
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
window.onload = initAll();
function initAll(){
var jsonData = {};
var xhr = false;
if(window.XMLHttpRequest){ //Chrome, Firefox, Opera, Safari, IE7+
xhr = new XMLHttpRequest();
} else if(window.ActiveXObject){ //IE5 + IE6
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Could not make XMLHttpRequest");
}
}
}
if(xhr){
xhr.open("GET", "js/ajax/test.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200){
try{
jsonData = JSON.parse(xhr.responseText);
alert(jsonData.title);
document.getElementById("vidtitle").innerHTML = xhr.responseText.title;
document.getElementById("vidcaption").innerHTML = jsonData.caption;
} catch(e){
alert("Unable to parse jsonData.");
}
}
};
xhr.send(null);
}
}
</script>
</head>
<body><div class="vidcontent">
<h2 id="vidtitle"></h2>
<p id="vidcaption"></p>
I'm doing this locally on my server, but I have uploaded the files to my web host and still get the same issues.
Firebug tells me it has the data and I can even read it through the console. Now, The code works in Firefox, but not Chrome or IE8 (IE8 Works occasionally when I put it into compatibility mode, but not always <.< ) I can't test on Safari or Opera right now.
Is there any way I can get this working in these browsers? I have attempted $.parseJSON in the JQuery library, but I was having issues with that as well. I am interested in JQuery as well if anyone can explain the solution with it.
Your JSON is invalid: http://www.jsonlint.com/
Leading 0's are not allowed in numbers apparently.

Categories