How do you modify a file using JavaScript together with PHP?

This is possible by using Javascript (front-end) to send an request to the PHP server script that does the operation (back-end).

What you can do is use jQuery.ajax or XMLHttpRequest.

XMLHttpRequest

var url = "addtext.php"; // Your URL here
var data = {
  text: "My Text"
}; // Your data here

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));

jQuery.ajax

var url = "addtext.php"; // Your URL here
var data = {
  text: "My Text"
}; // Your data here

$.ajax({
  url: url,
  data: data,
  method: "POST"
})

Note: There is also the jQuery.post method, but I have not included it.

And, in the PHP file, with the necessary permissions, you can write to the file using fwrite in combination with the other file functions.

<?php
$text = $_POST["text"]; // Gets the 'text' parameter from the AJAX POST request

$file = fopen('data.txt', 'a'); // Opens the file in append mode.
fwrite($file, $text); // Adds the text to the file
fclose($file); // Closes the file
?>

If you want to open the file in a different mode, there is a list of modes on the PHP website.

All the filesystem functions can be found here on the PHP website.

Leave a Comment