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.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器