Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_put_contents with jquery reload?

I currently have a problem with php and javascript. Here is the thing : I'm trying to edit every few second a text file stored on the server, with the text the client wrote in a textarea (which id is 'area1')

The PHP :

<span id="write">
    <?php
        if(isset($_POST['text']))
        {
                file_put_contents('file.txt', $_POST['text']);
        }
    ?>
</span>

The Javascript :

window.onload = function(){
    t = setInterval(load, 2000);

    function load()
    {
        $.ajax({
            type: "POST",
            url: "test.php",
            data: {
                text: $('#area1').val()
            },
            dataType: "text",
            success: function(data) {   
                $('#write').load('test.php #write');
            }
        });
    }
}

Nevertheless, nothing is ever written in file.txt, even if we enter the isset condition (that I tested).

Why isn't it working ? Can't we use jquery load with file_put_contents ? Or maybe it is a silly mistake that I can't see...

Thank you !

like image 579
Raphallal Avatar asked Nov 18 '25 00:11

Raphallal


1 Answers

Have you tried using $.post? It is simpler and clearer. Below is the full working code.

<html>
<head>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
</head>

<body>

<form>
    <textarea id="area1"></textarea>
    <textarea id="write"></textarea>
</form>


<script>
$(document).ready(function(){
    t = setInterval(load, 2000);

    function load()
    {
        $.post( "test.php", { text: $('#area1').val() })
            .done(function( data ) {
                    $('#write').load('test.php #write');
                    });
    }
});
</script>

</body>
</html>

And also make sure your php script has a privilege to add files. Use (sudo) chown apache *folder* or similar.

Good luck!

like image 182
Hett Avatar answered Nov 19 '25 12:11

Hett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!