Access local file from browser using jquery or Javascript - javascript

I'm trying to access local file from Browser. The file is located in Client Computer under C drive.
I tried different solution but all gave me error Access is denied.
I know that almost all browsers have disabled this functionality, but isn't there any setting we can do in browser or in client computer to make it work.
Someone told me to install browser extension to make it work, but I don't know how to do that.
try {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var lines = xmlhttp.responseText; //*here we get all lines from text file*
alert(lines);
}
}
xmlhttp.open("GET", "file:///E:\file.txt", true);
xmlhttp.send();
} catch (e) {
alert(e);
}
Any help will be highly appreciated.
Thanks

Unfortunately no, for security reasons you cannot automatically load a file from the user's Hard Drive.
What you can do is create an <input name="myFile" type="file"> and make the user manually select the file you need. This is the only way

Related

Loading a text file into javascript

I have a text file with a lot of values and I want to know if there is a way of loading these text file values into java script so that these values van be used by the script itself. Note I'm a newbie...
You haven't provided much context, but if we assume you mean "JavaScript running in a browser via an HTML page loaded from the same server as the text file", then you want to use the XMLHttpRequest object.
(Which is well documented in many places, so rather then providing yet another tutorial here, I'll let people use Google in the unlikely event of the above link breaking).
There are no shortage of libraries that abstract XHR. e.g. YUI, a host of tiny libraries and jQuery.
Assuming the text file is on your web server and you are loading from the browser, you could use jQuery like so:
jQuery.get('http://localhost/mytextfile.txt', function(data) {
alert(data);
});
Using XMLHttpRequest, you can achieve.
Example:
function ajaxCall() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
xmlhttp = ajaxCall();
xmlhttp.open('GET', 'YOURFILE.txt');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
}
with jQuery:
$('#result').load('ajax/test.txt');
Html code:
<div id="result">Text loaded here</div>
After loading the text will be replaced with the text file.

Why does my AJAX loading fail the first time through when hosting my MVC3 project in IIS7?

I was writing an mvc application with a few tabs. I noted that when hosted on IIS 7, the home page has a link triggering a JavaScript function to load content via AJAX.
It doesn't work on the first page load, however when I visit some other tab and come back to the home page and click on the link it works perfectly. Can someone tell me the reason for this or how to avoid it?
The Loading Code
function GetLabels(project) {
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("light").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", "/Home/GetLabels?project="+project, true);
xmlHttp.send();
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
document.getElementById("light").innerHTML =
"<img src='Content/load.gif' alt='Please wait' />";
}
The Link that Triggers it
Click here
You should not hardcode urls like this:
xmlHttp.open("GET", "/Home/GetLabels?project="+project, true);
You should always use url helpers to generate them:
xmlHttp.open("GET", "#Url.Action("GetLabels", "Home")?project=" + encodeURIComponent(project), true);
Now your AJAX request will work no matter whether you are hosting in Visual Studio's built-in server or IIS. The reason why your code doesn't work in IIS is because in IIS your application is hosted ni a virtual directory that you must include in your url. So the correct url is not /home/getlabels but /appname/home/getlabels which is something that the url helper takes into account.
Also since you are using a GET request the web browser might cache the result and never send a request again to the server. To avoid this you should append a random query string parameter to the url or use the POST verb.

Javascript XMLHttpRequest Invalid Argument

I'm currently working on a project trying to update a page reading from an XML file on our intranet server. After doing some working I came up with the following code:
// IE7+
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }
// IE6, IE5
else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET", "VerifiedUrl+XML.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
if (xmlDoc.getElementsByTagName("CheckBox")[0].childNodes[0].nodeValue == "True"){
document.getElementById("PartToUpdate").innerHTML = xmlDoc.getElementsByTagName("TextBox")[0].childNodes[0].nodeValue;
}
Now I've tested this code on my localhost and it does in fact read from the correct file, displaying the updated information, but when I deploy it to the intranet, I get an "Invalid Argument" error. (The XML file itself has been deployed and is referencing correctly).
Edit: I've recently found the problem, in that the path I was referencing apparently couldn't find the file itself. So that brings up another question that someone might be able to shed light on:
//When referencing a file within the same folder, it works correctly.
xmlhttp.open("GET", "Sample.xml", false);
//However, if I include the full path, it doesn't read correctly. (Double slashes to escape correctly)
xmlhttp.open("GET", "\\\\Full\\Server\\Path\\Here\\Sample.xml", false);
Perhaps someone could shed some light on this?
should your path be something like this:
xmlhttp.open("GET","./Path/Here/books.xml", false); //for relative urls
xmlhttp.open("GET","http://localhost/Path/Here/books.xml", false); //for absolute urls
and if its a non-http synchronous request
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
its not similar to your system path.
The path here is wrong:
xmlhttp.open("GET", "\\\\Full\\Server\\Path\\Here\\Sample.xml", false);
You are using the wrong type of slashes for the internet, they would be correct on a file system. It needs to use a forward slash.
xmlhttp.open("GET", "//Full/Server/Path/Here/Sample.xml", false);
Have you checked the same-origin policy?

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.

By using JS, it is possible to get a page source, and then respond users with this getting page

I want to implement the following things by using JavaScript:
using AJAX to get a page source;
put in some data into this page source;
show the changed page to users.
So it is possible? If so, how?
By the way, I cannot use server side technologies. And if JS is not suitable for it, what client technologies can be used in this case?
Assuming that the page you are wanting to get source from is on the same domain, you can get the page source like this:
if("XMLHttpRequest" in window){
xmlhttp=new XMLHttpRequest();
}
if("ActiveXObject" in window){
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open('GET', "URLofFileYouWantToGetTheSourceFrom", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText);
}
};
xmlhttp.send(null);

Categories