Jack_of_All_Trades
Jack_of_All_Trades

Reputation: 11468

Using AJAX to access file without extension

I want to fetch the content of a file in server without extension using AJAX. Simple demonstration of code is as follows:

<html>
<head>
<script>

function read_my_file(){

var xmlhttp;
if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }

xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
   document.getElementById ("myDiv").innerHTML=xmlhttp.responseText;
     }
}

xmlhttp.open("GET","MYFILE",true);// MYFILE HAS NO EXTENSION
xmlhttp.send();

}
</script>

</head>

<body>

<h2>THIS FETCHES DATA FROM SERVER IF WORKS!!!!!!</h2>
<button type="button" onclick="read_my_file()">Request data</button>
<div id="myDiv"></div>

</body>

</html>

As the file MYFILE has no extension, I think it is interpreted as folder name and I get 404 error. How can I fix this?

Upvotes: 0

Views: 908

Answers (2)

Chris Forrence
Chris Forrence

Reputation: 10094

If you want to load a file directly, it must be located within the web server's document root. That is, if the document root is /var/www/example.com/public, then you can access files like this:

  • /var/www/example.com/public/json/myfile.json
    • xmlhttp.open("GET","json/myfile.json",true);
    • xmlhttp.open("GET","http://www.example.com/json/myfile.json",true);

It can't, however, be accessed if the file is located at /var/files/json/myfile.json, since that lies outside the document root! You'd have to use a server-side language (such as PHP) to read the file.

Upvotes: 0

StackUMan
StackUMan

Reputation: 105

If chris's answer does not work you could also try and specify what mime-type your page should have using:

xmlHttp.overrideMimeType("application/xml");

or

xmlHttp.setRequestHeader("Accept", "text/html");

and simply replace "application/xml" or "text/html" with the type you need.

Upvotes: 1

Related Questions