简体   繁体   中英

trying to write to txt file with php and ajax post

I am trying to save a string that is created dynamically based on the user's interaction with the web app that I'm creating. just a string. nothing special. I am using ajax to send the string up to the server, and it seems that it is getting as far as the file_put_contents function I am using, but it seems to go haywire. It makes the txt file, but it does not put anything in it, and it does not send back q, the variable that I have it echo back.

Another weird thing is that when I try to write to said file with this

file_put_contents($putStringHere, $q);

I also tried this one:

file_put_contents($putStringHere, "$q");

The file always says that this happened:

modified: Today, Now (last time I ran the function)

Last Opened: Today, 5 minutes ago... last time I opened the file by hand

This would make sense, except for the fact that the function above contains fopen, fmodify, fclose, or whatever they're called. And the modified set to the last time I ran the function... I am super confused on this one. anyone who can help, I will greatly appreciate it.

ajax that sends string (yes, i made sure it was a string)

//ajax for saving changes
function stylesheetBackup(str){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","stylesheetBackupFile.php",true);
    console.log("q="+str);
    xmlhttp.send("q="+str);
}

also tried ajax with

xmlhttp.open("POST","stylesheetBackupFile.php",true);
xmlhttp.send();

php that I call with ajax

<?php
//get the q parameter from URL
$q = $_POST["q"];
$putStringHere = "savedStyleSheet.txt";
//output the response
echo $q;

//save to a backup file
file_put_contents($putStringHere, $q);
?>

You have a mis-match:

xmlhttp.open("GET"...

and

$q = $_POST["q"];

Here's two things that might help fix your problem:

  1. In the AJAX request, you specify that it's a GET request. However, in your PHP file, you're trying to get the q value of $_POST . Try $_GET['q'] instead.
  2. I'm not sure you're able to send your GET data using xmlhttp.send . Try adding it to your URL, as in xmlhttp.open("GET", "stylesheetBackupFile.php?q=" + str, true) .

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