Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top