I am trying to write a javascript function that tries reading text files from the server until it finds one that doesn't exist.
On the server there are text files numbered 1 to n (1.txt, 2.txt, 3.txt etc.), so it should read all the files (sequentially or asynchronously) until it tries to read "4.txt" and it throws an error.
The following code works on my local machine (with no server running), but fails on a remote server saying the "No such file" error is uncaught.
I am trying to understand why the error is handled differently in the two cases, if there is anything I can do to make it work for a remote server as well, and if there is any other approach I can take for this?
The minimal code I have is:
var files=[];
function readTextFile(file)
{
var request = new XMLHttpRequest();
request.open("GET", file, false);
request.onreadystatechange = function ()
{
if(request.readyState === 4)
{
if(request.status === 200)
{
var allText = request.responseText;
files.push(allText);
} else {
throw "No such file";
}
}
}
request.send();
}
function readFiles(){
try {
var i =1;
while (true) {
readTextFile(i+".txt");
i+=1;
}
}
catch (e) {
console.log("finished reading files")
}
console.log(files)
}
readFiles();
Related
I'm creating a website to progress in javascript and I have a little problem, every ways I try, my browser doesn't want to load my json file.
I tried many codes i found on internet but none of them work (or I don't know how to make them work). Finally i fond this one which is quite easy to understand but yhis one too doesn't work and always return an error message.
function loadJSON(path,success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 1) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path , true);
xhr.send();
}
function test()
{
loadJSON('test.json', function(data) { console.log(data); }, function(xhr) { console.error(xhr); });
}
I run the test function but everytimes, the console return me an error. Someone have an idea to solve my problem ?
status is the HTTP response code.
200 means the request has been successful. The status will most likely never be 1.
Here is a list of HTTP codes
As a solution, I suggest using the fetch API, which is the modern way to query files.
Here are some examples on how to use it
If you really want to use AJAX, use this :
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Source : You Might Not Need jQuery
In my website I am currently trying to write code to turn a link into a formatted attachment .
I am trying to write code to detect if the file exists
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
if (xhr.status == "404") {
return false;
} else {
return true;
}
}
alert(doesFileExist("http://hexbugman213.net/favicon.png"));
However, I noticed a problem. When the website has a 404 handler like .htaccess, and I try to test it with the file, it sees that the website didn't return a 404, and therefore still says it exists.
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
if (xhr.status == "404") {
return false;
} else {
return true;
}
}
alert(doesFileExist("http://hexbugman213.net/thisfiledoesntexist.mp3"));
Is there any way I can account for this and have it return "false" when the file doesn't exist even if there's a 404 handler?
You need to call the send() function on the XMLHttpRequest to make it actually make the request. See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
Also, you may run into cross origin issues depending on exactly what URL you're trying to retrieve and where you're hosting the page from. Mozilla has some documentation on the subject if you're not familiar with it: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Here is an improved version of your JavaScript that checks for exceptions and calls the send() function.
function doesFileExist(urlToFile) {
try {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
alert(xhr.status)
if (xhr.status !== 200) {
return false;
} else {
return true;
}
} catch (e) {
alert(e);
return false;
}
}
alert(doesFileExist("https://server.test-cors.org/server?enable=true&status=200&credentials=false"));
alert(doesFileExist("https://server.test-cors.org/server?enable=true&status=404&credentials=false"));
alert(doesFileExist("https://www.google.com/"));
alert(doesFileExist("http://hexbugman213.net/thisfiledoesntexist.mp3"));
The host: https://www.test-cors.org/ in the example is useful for testing CORS.
I'm trying to write a VSTS extension that needs to load (and parse) a JSON file but I'm having a hard time finding the right way to do it.
So I have something like:
VSS.init({
explicitNotifyLoaded: true,
usePlatformScripts: true
});
var witClient;
var rules;
VSS.ready(function () {
require(["fs"], function (fs) {
rules = JSON.parse(fs.readFileSync("urlMatches.json"));
})
VSS.require(["VSS/Service", "TFS/WorkItemTracking/RestClient"], function (VSS_Service, TFS_Wit_WebApi) {
// Get the REST client
witClient = VSS_Service.getCollectionClient(TFS_Wit_WebApi.WorkItemTrackingHttpClient);
});
// Register a listener for the work item page contribution.
VSS.register(VSS.getContribution().id, function () {
return {
// Called after the work item has been saved
onSaved: function (args) {
witClient.getWorkItem(args.id).then(
function (workItem) {
// do some stuff involving the loaded JSON file...
});
}
}
});
VSS.notifyLoadSucceeded();
});
I've tried a bunch of variations on this without any luck. I've even tried using jQuery to load my file synchronously and yet my rules ends up undefined.
So I have the file urlmatches.json and I need to load it and use it to populate the variable rules before I get to the onSaved handler.
You can retrieve content through HTTP request, for example:
onSaved: function (args) {
console.log("onSaved -" + JSON.stringify(args));
var request = new XMLHttpRequest();
request.open('GET', 'TestData.txt', true);
request.send(null);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var type = request.getResponseHeader('Content-Type');
console.log(request.responseText);
}
}
I've written the following JavaScript function which is very simple, it takes an ID and which then is sent to a PHP page, which echoes out some JSON. It passes the ID into the PHP page via GET.
For example, if I was to make the following GET request: /processing/getAccountInfo.php?id=5, it would return this (got from a database): {"username":"carefulnow","profileImg":null}. This is correct, so I know my PHP is working fine.
My JavaScript code that originally called the AJAX now needs to process it, echo it out and check it for errors. If the PHP function encounters any errors, the returned JSON will contain an "errorMsg" which contains the name of the PHP exception that it encountered including a specific message (Exception::getMessage()). An example error result would be {"errorMsg":"PDOException: some error..."}.
function getAccountInfo(id) {
var loading = document.getElementById("loading");
var inner = document.getElementById("accInfInner");
var name = document.getElementById("accInfName");
var img = document.getElementById("accInfImg");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
try {
var response = JSON.parse(this.responseText);
if (response.errorMsg === undefined) {
if (response.username === undefined || response.profileImg === undefined) {
throw new Error("Could not get the username and profile image. Try logging in then back out.");
}
name.innerHTML = response.username;
// The profile image is not required.
if (response.profileImg !== null) {
img.src = response.profileImg;
} else {
img.src = "/assets/img/defaultuser.jpg";
}
loading.style.display = "none";
inner.style.display = "block";
} else {
throw new Error(response.errorMsg);
}
} catch (exception) {
inner.innerHTML = "Error. Hover for details.";
inner.title = exception.message;
}
}
};
xmlhttp.open("GET", "/processing/getAccountInfo.php?id=" + id, true);
xmlhttp.send();
}
The problem, however, is that the throw statements aren't working. If an error is thrown from the PHP, nothing happens (no errors in the console)! My IDE (PHPStorm 2017.1) gives the following error: "'throw' of exception caught locally", which after a lot of searching, I cannot find anyone else having this same issue. Is it something to do with the GET request been asynchronous, or is it something a lot simpler I'm not seeing?
I would like to retrieve fullpath of a file and pass it to javascript. The requirement is that I need to retrieve XML file using JavaScript.
If it is a file you can access relatively to your web page do something like:
var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false";
xmlDoc.load("abc.xml");
Assuming you have your web page next to the abc.xml...
This doesn't specify how to get full path to the XML - do youi still need it or loading it is enough?
For cross browser (from: http://developer.apple.com/internet/webcontent/xmlhttpreq.html)
var req;
loadXMLDoc("abc.xml");
function loadXMLDoc(url) {
req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send("");
}
}
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
alert(req.responseXML);
} else {
alert("There was a problem retrieving the XML data:\n" + req.statusText);
}
}
}
If you know the exact file up front, you can create a server-side program (i.e. service) to read the file, parse it and output it.
Then you'll just need to write some Javascript to make an AJAX call to this service (check out a Javascript library like Prototype or JQuery) to read the output of the service and thus the contents of the file.