I have this basic HTML page and there is a form to upload data to a MySQL database.
There is also a JavaScript that passes data to the process.php file. Into this file, I have an INSERT query. I use this script because I do not want to reload the page on submit.
Now I have 2 problems:
1) When I send data to the MySQL table (clicking on submit button), the first time 1 data = 1 record inserted and this is correct. If I insert a new data into the input form field, I have 1 data = 2 records equal. The third time, 3 records and so on...
But if I print what is passed by POST with print_r($_POST), I have always one data Array ( [comune] => foo ).
I also tried to use unset() without success.
2) When I click for the first time on submit button, there's no action, I have to click twice.
This is the HTML page with the JS script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".formValidation").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
},
submitHandler: function(form) {
// do other stuff for a valid form
$('.formValidation').on('submit', function () {
$.post('process.php', $(this).serialize(), function(data){
$('#results').html(data);
});
})
}
});
});
</script>
</head>
<body>
<div class="row">
<div class="col-xs-12">
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<div class="col-xs-12 col-sm-4">
<div class="widget-box">
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">form</label>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Add something" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<p id="result"></p>
<div id="results"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</body>
</html>
and the process.php
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
unset($key);
unset($value);
}