简体   繁体   中英

ajax not posting to text file

I am learning ajax and I have followed a tutorial to post some data to a text file via a php script but I can't get it to work. Is there something I have missed.

the following is the ajax.html page which is a input text with a button to post the data via ajax

 <form name="testform"> Off Min:<input name="setOffMin" type="text" id="setOffMin" maxlength="2" size="1"/></br> <button type="button" onclick="postStuff();">Submit</button> </form> <div id="status"></div> <script type="text/javascript"> function postStuff(){ var hr = new XMLHttpRequest(); var url = "update.php"; var offM = document.getElementById("setOffMin").value; hr.open("POST", url, true); hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); hr.onreadystatechange = function(){ if (hr.readyState == 4 && hr.status == 200){ var return_data = hr.responseText; document.getElementById("status").innerHTML = return_data; } } hr.send(offM); document.getElementById("status").innerHTML = "processing..."; } </script> 

this is the update.php file

 <?php

         $setOffMin = $_POST["offM"];
         $f = fopen("test.txt", "w");
         fwrite($f, $setOffMin);
         fclose($f);
 ?>

I have been looking over this code all last night and cannot work out why it is not writing the data to the text file. I have run the php script editing out the $_POST and putting in a variable and it does write to the text file. So the php should work and the text file permission is correct. I expect this is the ajax that I have done wrong. any help will be great

You need to send offM as urlencoded like this:

var offM = 'offM='+document.getElementById("setOffMin").value;

Now when you click on Submit you call update.php?offM=YourText and PHP recieve var $_POST['offM'] with value YourText

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM