Run a PHP function from javascript file

I have tried using Ajax and also tried using the javascript fetch api, but they both give the same "Could not find resource write.php", but when I actually go to the write.php file on the webpage, there is no error. Here is my current code which does not work:

javascript:

var email = "EMAIL"
$.ajax({
  method: "POST",
  url: "write.php",
  data: { text: email }
})
  .done(function( response ) {
    console.log(response);
});

php:

function write_log($string) {
    $log_file = './data/cool.html';       
    fopen($log_file, "a+");
    fwrite($log_file, $string + "\n");
    fclose($log_file);
}
$text = $_POST['text'];
$output = write_log($text);
echo $output;

sorry if I didn’t clarify enough in the question, haven’t been on stack overflow for a while

1 thought on “Run a PHP function from javascript file”

  1. when I actually go to the write.php file on the webpage

    What do you type in your browser (or what argument do you give to curl or wget) to "go to" the file?

    Try using that in place of "write.php" in your javascript.

    Reply

Leave a Comment