Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  167] [ 2]  / answers: 1 / hits: 153598  / 11 Years ago, sat, march 30, 2013, 12:00:00

Is it possible to save text to a new text file using JavaScript/jQuery without using PHP? The text I'm trying to save may contain HTML entities, JS, HTML, CSS and PHP scripts that I don't want to escape or use urlencode!



If it's only can be achieved using PHP how can I pass the text to PHP without encoding it?


More From » jquery

 Answers
25

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.


[#79222] Friday, March 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dequant

Total Points: 88
Total Questions: 99
Total Answers: 95

Location: Ukraine
Member since Sun, Dec 13, 2020
4 Years ago
dequant questions
;