0

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.";
    }
?>
3
  • I think putting print_r($_POST['itemName']) somewhere in your PHP will help you. Commented Jul 3, 2013 at 23:00
  • You might find the jQuery Form Plugin helpful: malsup.com/jquery/form Commented Jul 3, 2013 at 23:06
  • adding print_r does help. I can see that now my form is submitting the information as an array. I just need to find out a way to strip these out and insert them seperately but to the same parent id. what i got in return was: The id of the inserted information is Array ( [0] => sdsdsd [1] => sdsd [2] => asdasdasd ) Commented Jul 3, 2013 at 23:08

4 Answers 4

1

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();
Sign up to request clarification or add additional context in comments.

8 Comments

Hey mate, the problem with the second option is that there is no predefined amounts, the user will add the input fields they need so it needs to be automatic. Doing the first option seems to break the system, though i would assume that's my fault. The php is killed. Any suggestions?
@AndyHolmes give all the inputs a class then select them by their class. $('.input_class').serialize()
Its okay, i missed the [] in my php script. It's now printing an array like - The id of the inserted information is Array ( [0] => sdsdsd [1] => sdsd [2] => asdasdasd ). Just need to split these and add them seperately to the database. Will i need to use something like an unserialize?
@AndyHolmes its an array so you just reference them through their index. [0] will give you sdsdsd etc
Can you give me an example? Not entirely 100% on the whole array thing at the momen
|
0

$_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.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.