autosave ajax, php
I'm trying to make an autosave function with prototype and PHP but it doesn't work.
If I change $('txtdoc').value to "any text", then "any text" is saved without any problems in the database
JS
document.observe("dom:loaded", function() {
intervalID = window.setInterval("autosave()",1000);
});
function autosave() {
new Ajax.Request('autosave.php?id=<?php echo $_GET["id"];?>',
{
method: 'post',
parameters: {txtdoc:开发者_如何学运维 $('txtdoc').value},
});
}
autosave.php
<?php
include '../../db.php';
if(isset($_POST["txtdoc"])){
$did = mysql_real_escape_string($_GET["id"]);
$txtdoc = mysql_real_escape_string($_POST["txtdoc"]);
$sql="UPDATE doc SET txt = '$txtdoc' WHERE id = '$did'";
mysql_query($sql);
}
?>
Form
<form action="" method="post">
<textarea id="txtdoc" name="txtdoc" style="width:605px; height:200px;"><?php echo $txt; ?></textarea>
<input type="submit" value="Save"/>
</form>
<script>
autosave();
</script>
If you are using prototype, then (unless you have a reason why it doesn't work) you are probably best off using it...
Create a hidden div:
<div id="dummy" style="display: none"></div>
Then try this:
document.observe('dom:loaded', function() {
new Ajax.PeriodicalUpdater(
'dummy',
'autosave.php?id=<?php echo $_GET["id"];?>', {
method: 'post',
parameters: {
txtdoc: $F('txtdoc')
}
}
, 10)
});
What this does is use the PeriodicalUpdater (triggering every 10 seconds) to call your PHP script. The parameter is read using $F (The unified field reader method).
Additionally, I notice you had a trailing comma after the parameters: object. This will fail on IE as it doesn't allow trailing commas.
精彩评论