简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM