Andy Holmes
Andy Holmes

Reputation: 8077

Submitting form input array via ajax and saving with mysql/php

I've got some code below which has been working fine for one input field. However I have some code that appends extra fields into the form if you click a div called #addForm, and the inputs have the name of name="itemName[]".

<script>
    $(document).ready(function() {
        $('body').on('click', '.save', function(e) {
            var string = $(this).serialize();
            $.ajax({
                type: "POST",
                url: "add_room.php",
                data: string,
                cache: false,
                success: function(data){
                    $('#message').text('The id of the inserted information is ' + data);
                }
            });
        });
    });
    $(document).ready(function(){
        $('#addForm').on('click', function(){
            $('<label for="itemName[]">Item</label><input class="itemName" type="text" name="itemName[]"><label for="itemCondition">Condition</label><input class="itemCondition" type="text" name="itemCondition"><div class="save">Save Item</div>').fadeIn(500).appendTo('#mainForm');
        });
    });
    </script>

As you can see, I've got most of the code there, yet I get confused with serialize and I'm not sure how I should be handling this on the php end.

This is my script so far for the php:

<?PHP

    include('dbConfig.php');

    $item = $db->real_escape_string($_POST['itemName']);

    if ($stmt = $db->prepare("INSERT test (test_title) VALUES (?)"))
    {
        // Use an s per variable passed to the string, example - "ss", $firstname, $lastname
        $stmt->bind_param("s", $item);
        $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 SQL statement.";
    }
?>

Upvotes: 0

Views: 5047

Answers (4)

G&#246;khan Girgin
G&#246;khan Girgin

Reputation: 1164

Form

<form method="POST" class="save" action="add_room.php">
<input type="text" name="itemName[]"/>
<input type="text" name="itemName[]"/>
<button type="submit">Save</button>
</form>

jQuery

$(document).on("submit",".save",function(e){
e.preventDefault();
$.post($(this).attr("action"),$(this).serialize(),function(r){
//result
alert(r);
});
});

jsFiddle

PHP

$item = $_POST['itemName']

foreach( $item as $key => $val ) {
  //iterate itemName values
}

PhpFiddle

Upvotes: 0

Mark Zhou
Mark Zhou

Reputation: 13

From my point of view

var string = $(this).serialize();

this in the above context is most likely to be reference of the DOM element which has a class name save, it could be a button for submission of the form.

However, the correct element that serialize() is called of should be a form element.

I think that's why you can't get anything from server side,

$_POST['itemName']

I suggest, you can start with have a look at $_POST object, then figure out how to extract the data you need from it.

Hope it helps

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71394

$_POST['itemName'] is going to be an array. You need to treat it as such (i.e. not try to perform real_escape_string() on it).

You would also need to either loop through the array doing separate insert queries, or build a single query which insert all values.

From a javascript standpoint, I am guess you need to serialize the form as opposed to the button that is clicked. I just noticed @Musa posted an answer on this, so follow that instruction.

Upvotes: 0

Musa
Musa

Reputation: 97707

You call serialize on a <form> or a set of form fields and not a button (I guess)
If the button is in the form then try,

var string = $(this).closest('form').serialize();

if you don't have a form just select all the inputs you need

var string = $('#input1,#nextone,#somefield').serialize();

Upvotes: 1

Related Questions