1

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

3
  • xmlhttp.open("POST","test1.txt",true); post to a PHP script that reads the data & writes the file – Alex K. Nov 16 '14 at 20:44
  • That indeed explains why it doesnt work! Thank you! Do you have any example of the missing PHP-script? I know how to use fwrite but I dont know how PHP gets the data that Ajax posts? – Joel Nov 16 '14 at 21:13
  • I don't use PHP, but how about write to a text file from HTML form using PHP – Alex K. Nov 16 '14 at 21:17
1

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);
?>  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.