-6

I want to add text to a text document using JavaScript and PHP. What would be the best way to do this?

Maytha8
  • 846
  • 1
  • 8
  • 26

2 Answers2

1

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.

Maytha8
  • 846
  • 1
  • 8
  • 26
0

I don't think you can append to a text document unless you are writing server side code.

There are some possible workarounds mentioned in this post: Is it possible to write data to file using only JavaScript?

doublea
  • 447
  • 1
  • 4
  • 11