duanniubeng2265 2013-07-09 21:37
浏览 68
已采纳

jQuery自动保存不能正常工作

I have a couple of scripts i have written below that work great seperately, but together they don't work as they should. Let me post the code and then explain the issue:

Autosave function:

<script>
        function autosave() {
            $('form').each(function() {
                var string = $(this).closest('form').serialize();
                var $this = $(this);
                $.ajax({
                type: "POST",
                url: "add_room.php",
                data: string,
                cache: false,
                success: function(data){
                    var saveIcon = $this.siblings('.saveIcon');
                    $this.siblings('[type=hidden]').val(data);
                    saveIcon.fadeIn(750);
                    saveIcon.delay(500).fadeOut(750);
                    $('#message').text('The id of the inserted information is ' + data);
                }
                });
            });
        }
        setInterval(autosave, 10 * 1000);
</script>

AJAX post and return script:

<script>
    $(document).ready(function() {
        $('body').on('click', '.save', function(e) {
            var string = $(this).closest('form').serialize();
            var $this = $(this);
            $.ajax({
                type: "POST",
                url: "add_room.php",
                data: string,
                cache: false,
                success: function(data){
                    var saveIcon = $this.siblings('.saveIcon');
                    $this.siblings('[type=hidden]').val(data);
                    saveIcon.fadeIn(750);
                    saveIcon.delay(500).fadeOut(750);
                    $('#message').text('The id of the inserted information is ' + data);
                }
            });
        });
    });
    $(document).ready(function(){
        $('#addForm').on('click', function(){
            $('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
        });
    });
</script>

Form:

<form method="post" action="add_room.php">
                <label for="itemName[]">Item</label>
                <input type="text" name="itemName[]">
                <label for="itemPhoto[]">Item</label>
                <input type="text" name="itemPhoto[]">
                <input type="hidden" name="itemId[]" value="">
                <input type="hidden" name="itemParent[]" value="<?=$_GET['room']?>">
                <div class="saveIcon" style="display: none; color: green;">SAVED!</div>
                <div class="save">Save Item</div>
</form>

PHP:

<?PHP

    require_once('dbConfig.php');

    $item = $_POST['itemName'];
    $photo = $_POST['itemPhoto'];
    $id = $_POST['itemId'];
    $parentId = $_POST['itemParent'];

    foreach($item as $key => $val) {

        if(!$id[$key]) {

            if ($stmt = $db->prepare("INSERT test (test_title, test_desc, test_parent) VALUES (?, ?, ?)"))
            {
                // Use an s per variable passed to the string, example - "ss", $firstname, $lastname
                $stmt->bind_param("ssi", $val, $photo[$key], $parentId[$key]);
                $stmt->execute();
                $stmt->close();

                echo $db->insert_id;
                //echo "success";
            }
            // show an error if the query has an error
            else
            {
                echo "ERROR: Could not prepare Insert SQL statement.";
            }

        } 
            else
        {
            if ($stmt = $db->prepare("UPDATE test SET test_title = ?, test_desc = ? WHERE test_id = ?"))
            {
                // Use an s per variable passed to the string, example - "ss", $firstname, $lastname
                $stmt->bind_param("ssi", $val, $photo[$key], $id[$key]);
                $stmt->execute();
                $stmt->close();

                echo $id[$key];
                //echo "success";
            }
            // show an error if the query has an error
            else
            {
                echo "ERROR: Could not prepare Update SQL statement.";
            }
        }

    }

?>

Now, what happens with the second script is, when used on its own without the autosave, when you fill out the form and click save it takes that forms data and saves it to the necessary rows in a database, and then returns the id of what was just saved and puts that data in a hidden field so that the php script can work out if an insert query is needed or an update query is needed(when the returned id is present). There is also a clickable div called addForm which then appends another form set below the one(s) present and again, when it's save button is clicked ONLY this form is saved/updated in the database. When i trigger the autosave like i have in my code, the autosave literally takes ALL the forms and saves them as new entries but doesn't return the id/update the hidden field to trigger the update sequence. Can you shed ANY light on this at all? It's really bugging me. Have tried explaining this as best i can, sorry it's so long. It's a bit of a complicated one! haha

  • 写回答

1条回答 默认 最新

  • dpmir1988 2013-07-09 23:46
    关注

    I'd suggest a few changes to the organization of the code, which then leads to making it easier to identify the errors.

    http://pastebin.com/0QTZzX6X

    function postForm(form) {
        var $this = $(form);
        var string = $this.serialize();
        $.ajax({
            type: "POST",
            url: "add_room.php",
            data: string,
            cache: false,
            success: function(data){
                var saveIcon = $this.find('.saveIcon');
                $this.find('[type=hidden]').val(data);
                saveIcon.fadeIn(750);
                saveIcon.delay(500).fadeOut(750);
                $('#message').text('The id of the inserted information is ' + data);
            }
        });
    }
    
    function autosave() {
        $('form').each(function() {
            postForm(this);
        });
    }
    setInterval(autosave, 10 * 1000);
    $(document).ready(function() {
        $('body').on('click', '.save', function(e) {
            postForm($(this).closest('form').get(0));
        });
    
        $('#addForm').on('click', function(){
            $('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
        });
    });
    

    Basically i took logic that was duplicated and placed it into a more generic function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏