简体   繁体   中英

Why won't my ajax AutoSave work?

I'm using a script found on this page: http://jetlogs.org/2007/11/11/auto-saving-with-jquery/ to autosave a form I have. I'm only trying to save the textarea for the form. Here's the relevant code:

<head>
    <script type="text/javascript">
        $(document).ready(function(){           
            autosave();
        });

        function autosave()
        {
            var t = setTimeout("autosave()", 5000);

            var comments = $("#comments").val();

            if (comments.length > 0)
            {
                $.ajax(
                {
                    type: "POST",
                    url: "autosave.php",
                    data: "rubric_id=" + <?php echo $rubricid ?> + "&student_id=" + <?php echo $studentid ?> + "&comments=" + comments,
                    cache: false,
                    success: function(message)
                    {   
                        $("#autosave_status").empty().append(message);
                    }
                });
            }
        } 
        </script> 
</head>
<body>
<div id="autosave_status"></div>
<form action='assess.php?student=146&rubric=19' method='POST'>
<textarea id="elm1" name="comments" rows="15" cols="80" style="width: 80%">
</form>
</body>

And here's the PHP:

<?php
//include DB configuration file
  include "../../signout/database.php";


$comments = mysql_real_escape_string($_POST['comments']);
$rubric_id = (int)$_POST['rubric_id'];
$student_id = (int)$_POST['student_id'];



//save contents to database
$sql = "UPDATE rubrics_comments SET comments = '$comments' WHERE studentid = '$student_id' AND rubricid='$rubric_id'";
mysql_query($sql) or die (mysql_error());
echo $sql;



//output timestamp
echo 'Saved';

?>

It seems almost as though the ajax isn't even working, since I'm not seeing any display changes or error messages on the page where the form is located.

Any ideas? Thanks!

your textarea has an id of elm1

<textarea id="elm1" name="comments" rows="15" cols="80" style="width: 80%">

but your trying to access it by

$("#comments")

change to

$("#elm1")

or

$("[name=comments]")

Your textarea's id is not "comments". And you're using an id selector $("#id");

Two things:

change

 var comments = $("#comments").val();

to

 var comments = $("#elm1").val();

And close your textarea element:

</textarea>

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