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

11 thoughts on “Run a PHP function from javascript file”

Leave a Comment