Search code examples
javascriptjqueryajaxtext

Saving a text file on server using JavaScript


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?


Solution

  • 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.