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.";
}
?>
print_r($_POST['itemName'])somewhere in your PHP will help you.