You must have a server-side script to handle your request, it can't be done using javascript.
To send raw data without URIencoding or escaping special characters to the php and save it as new txt
file you can send ajax request using post
method and FormData
like:
JS:
var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);
PHP:
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
Edit:
As Florian mentioned below, the XHR fallback is not required since FormData
is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:
var xhr = new XMLHttpRequest();
Also please note that this works only for browsers that support FormData
such as IE +10.