How to Create a File using jQuery, Ajax and PHP

How to Create a File using jQuery, Ajax and PHP

In this article we are going to see how to write or create a text file using jQuery, Ajax and PHP. We will use these technologies just for the simple fact of not having to reload the page after submitting the form.

In the working example have a form with a textarea field where you input the text we want to save the file. For security reasons, we have disabled the option to enter HTML code.

In the <body> of our website we will have the following form:

<form id = "form" method = "post">
    text: <br/>
    <textarea name = "data" id = "data" rows = "7" cols = "84" placeholder = "Enter text here ..."> </ textarea>
    <a href="#" id="save"> Save </a>
</ form>

Where you just have a text field (textarea) and a button or link.

In the <head> of this page will include the jQuery library and the necessary scripts to perform the core functionality of the example:

<script src = "// ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </ script>
<script type = "text / javascript">
$ (document) .ready (function () {
    $ ( '# save'). live ( 'click', function () {
        datastring var = 'data =' + $ ( 'textarea # data') val ().;
        $ .ajax ({
            type: "POST"
            url: "writetxt.php"
            data: datastring,
            success: function (data) {
                // alert (data);
                $ ( 'form') remove ().;
                . $ ( '. content') append ( '<p> Your text has been successfully saved </ p> <a href="data.txt" target="_blank"> View </a>!');
            }
        });
        return false;
    });
});
</ Script>

The code above is just waiting for you to press the button or link with id = “save” to capture the information entered in the text field with id = “data” (textarea) and by the technique AJAX send that information to a php file that will be responsible for writing this information sent on the .txt file.

The .php file will have the following content:

<? php
require_once ( "classes / class.inputfilter.php");
$ ifilter inputFilter = new ();
$ data = $ ifilter-> process ($ _ POST [ 'data']);
$ file = 'data.txt';

if (isset ($ data)) {
    $ fp = fopen ($ file, 'w');
    fwrite ($ fp, utf8_decode ($ data));
    fclose ($ fp);
    chmod ($ file, 0777);
    echo 'You have successfully saved the information in txt!';
}
else {
    echo 'No data to save!';
}
?>

In this file the first thing we do is receive data sent by the POST method and use a technique to prevent XSS with class inputfilter PHP, so if there is information to save, open the file and write on it the information received.

Lucid Kit

Related Posts
Leave a reply
Captcha Click on image to update the captcha .