Reputation: 93
I've been struggling to write server text files with Ajax and would really appreaciate if someone had a moment to take a look. In simple, why doesnt the following code write 'testdata' to test1.txt?
<!DOCTYPE html>
<html>
<head>
<script>
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)
{
alert('done')
}
}
xmlhttp.open("POST","test1.txt",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("testdata");
</script>
</head>
<body>
</body>
</html>
I've successfully been able to read text files with GET. If I replace the 3 key lines with
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
it works.
What is wrong with the code above or is this a file permission issue? I am using GoDaddy and given writing permission so that I can modify the above text file with php for example.
Any help is greatly appreciated.
Thanks in advance!
Joel
Upvotes: 2
Views: 9824
Reputation: 93
Got it working now - thanks Alex! These are the working files:
<!DOCTYPE html>
<html>
<head>
<script>
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)
{
alert('done')
}
}
xmlhttp.open("POST","phpwrite2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=Joel");
</script>
</head>
<body>
</body>
</html>
And PHP:
<?php
$myFile = "ttt.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_POST["name"];
fwrite($fh, $stringData);
fclose($fh);
?>
Upvotes: 2