Using AJAX to access file without extension - javascript

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?

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.

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.

Related

XMLHttpRequest does nothing....?

I am new to javascript and AJAX, and have spent the last 8 hours on this one problem, and its beating me. I know its simple, just can't find what I am doing wrong. I have an image on my site with a with an on-click=SendCommand() . This is the js code that I have
function SendCommand(){
alert("BingoBango!");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
};
I get the alert message, and I get no errors using firebug or in chrome javascript console. However that page is not executed. I can however copy and paste that exact url into the browser and it executes successfully.
Any help would be GREATLY appreciated, its kickin my butt.
The page it is calling is calling a python script as well as updating a mysql record. Is there something i can do in my request to ask it to not use the browser cache and actually hit my server?
You should not use a GET request for things that execute actions on the server. Use POST instead, which should not be cached.
If that doesn't help, adapt your HTTP cache headers or, as a last resort, append random strings to the url.
This is how I would do it
JS
function SendCommand()
{
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","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
}
HTML
<button type="button" onclick="SendCommand()">My button</button>
<div id="myDiv"></div>

When you link a script, is it automatically run?

The reason I am asking this is because in one of my pages I link a javascript script and then when I try to run a function in the javascript file, it doesn't work.
This is weird because when I copy the exact same code from the script file and put it between the tags, the function then works fine.
Here is how I linked it:
<script src="../scripts/login.js" type="text/javascript"></script>
Here is how it is referenced:
<td><button type="button" onclick="login()">log in </button></td>
Here is the javascript file in case you want to see it:
function login()
{
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)
{
username = encodeURICompenent(document.getElementById("username").value);
password = encodeURICompenent(document.getElementById("password").value);
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
If you attach an external JavaScript file to your document and it contains code that were not found inside any method written on function declaration syntax. those code would execute right after the browser parses the JavaScript file.
Ex.
function CallMe() {
console.log("I'm going to execute once callMe method is invoke");
}
console.log("I'm going to execute once browser parses the javascript file");
The login method on your case wont execute unless there is an event that triggers/invokes the click event of your button.

getting xmlDocument object

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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)
{
xmlDoc=xmlhttp.responseXML;
}
}
xmlhttp.open("GET","cd_catalog.xml",true);
xmlhttp.send();
}
</script>
</head>
<body>
<script>
loadXMLDoc();
alert(xmlDoc)//dont work
if(xmlDoc){console.log("true")}
else(console.log("false"))
</script>
<div id="myDiv"></div>
</body>
</html>
If i try to access xmlDoc from within the body then the code does not work??Also i tried to know whether xmlDoc exist using if statement within the body like:
if(xmlDoc){console.log("true")}
else(console.log("false"))
but this also fails ,i m new to xmlDom so what mistake have i made above ?thanks
xmlhttp.open("GET","xmlhttp_info.txt",false);
sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:
execute other scripts while waiting for server response &
deal with the response when the response ready
So this is the reason why ur alert within the body doesn't work since js will continue to execute code.
using async=false JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.
Remember that async=false is not recommended, but for a few small requests this can be ok.

Send or get data from mysql using php ajax jquery - what is the secure method?

I have use Ajax and jquery for get data from database and send data, but when we use ajax or jquery methods, web page source view ,we can see details like below;
Ajax
<script type="text/javascript">
function showUser()
function showUser()
{
var str = document.getElementById('txtusername').value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="<span style='color:#FFF;font-size:10px;'>Enter username</span>";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","chkusername.php?q="+str,true);
xmlhttp.send();
}
</script>
In here you can see the get method and what are the sending values and also more things. I want hide these thing from source view, help me ..
You can't. Anything on the client side (HTML, CSS, JavaScript) is free for the user to see.
That's why anything security-related is on the server side, where it can be trusted (for the most part).
It's not a security risk if the user knows that to log in you go to /chkusername.php?q=username (or whatever). It is one, however, if you don't properly sanitise the input.

Load HTML using loaded document's path as root for its relative paths instead of source document's path

Well I have something like this,
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
Loading your content...
</body>
<script type="text/javascript">
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)
{
$("body").html(xmlhttp.responseText);
}
};
xmlhttp.open("GET","../stats.phtml",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
</script>
</html>
And it doesn't found any external documents linked in the loaded document stats.phtml (javascript and css sources), because the path for the relative paths is the path where the document is, instead of the loaded document's root path.
I need to do this on AJAX (the loading page is supposed to be executing a script while the content is being loaded and show it after 3 seconds have passed), so just doing window.location='../stats.phtml' after the 3 seconds is not a good solution. I'd also like to keep the relative links in the loaded doc instead of moving them to absolute ones. Any suggestions?
I found out reading this article on mozilla developer that html5 window.history.pushState can be used before making the substitution, like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var stateObj = { foo: "stats" };
window.history.pushState(stateObj, "Title", "../stats.phtml");
$("body").html(xmlhttp.responseText);
}
Wich is fair enough for me.
Otherwise, I read # marks can be used to identify the documents and switch one URL for the other without reloading (in combination with some Apache modrewrite spells to change the # notation to actual directories in the server, I guess). If you know exactly how, any example using this approach would be appreciated.
update I've been working on this for some time and I found a non-jquery alternative which replaces the whole document content and suits me better in this case.
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var stateObj = { foo: "stats" };
window.history.pushState(stateObj, "Title", "../stats.phtml");
document.open('text/html');
document.write(xmlhttp.responseText);
document.close(); // don't forget to do this, or you'll be in trouble!
}
Enjoy!

Categories