File_put_contents with jquery reload?
I am currently having a php and javascript problem. Here's what: I am trying to edit every few seconds a text file stored on the server with the text the client wrote in the text box (which id is "area1")
PHP:
<span id="write">
<?php
if(isset($_POST['text']))
{
file_put_contents('file.txt', $_POST['text']);
}
?>
</span>
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');
}
});
}
}
However, nothing is written to the .txt file even if we put in the isset condition (which I tested).
Why isn't it working? Can't we use jquery upload with file_component? Or maybe it's a stupid mistake that I can't see ...
Thank!
+3
source to share
1 answer
Have you tried using $ .post? It's simpler and clearer. Below is the complete 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>
Also, make sure your PHP script has the add files privilege. Use (sudo) chown apache *folder*
or similar.
Good luck!
+1
source to share