简体   繁体   中英

javascript/php to save string in file on server

I am fairly new to javascript and php. I am trying to save a variable in javascript in a simply text file on the server. I understand that javascript operates on the browser so I can't use javascript directly. I am trying to pass the string to a php file and save it there but it is not working. Any advice would be appreciated. Here is the javascript:

var data = "test"
var url = "save-to-log.php";
var XML = "data.txt";
if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } 
else
            {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
xmlhttp.open("POST",url,true);
xmlhttp.send("D="+data+'&F='+XML);

and here is the php file which is on the server:

<?php
$NAME = $_POST['F'];
$HANDLE = fopen($NAME, 'w') or die ('CANT OPEN FILE');
fwrite($HANDLE,$_POST["D"]);
fclose($HANDLE);
?>

As you send data as POST param you need to set header application/x-www-form-urlencoded

xmlhttp.open("POST",url,true);
// this line 
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');  
xmlhttp.send("D="+data+'&F='+XML);

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