I'm looking for a way to submit multiple dynamic form fields in a single submission.
Each row of data when submitted will share certain attributes:
job id, client, type of work.
While also keeping their own independent variables:
role, name, tvl, start date, end date, start time, end time.
I think my solution will either require a for loop or the use of multi dimensional arrays (maybe both?) but I can't quite figure out where in my code to implement that or how to do so.
At the moment - only 1 "employee" is showing up in my database - typically the last entry made in the "details" div.
Here is the code:
HTML
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<head>
</head>
<body>
<form method="POST" action="include/ajax.inc.php" class="ajax">
<h2>Job Details</h2>
<br>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Job ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="a" id="a">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Client</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="b" id="b">
<option value="" disabled selected>Select</option>
<option value="OPTION1" name="OPTION1">OPTION1</option>
<option value="OPTION2" name="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type of Work</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="c" id="c">
<option value="" disabled selected>Select</option>
<option value="OPTION1" name="OPTION1">OPTION1</option>
<option value="OPTION2" name="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<h2>Employee Details</h2>
<button class="btn btn-lg btn-primary btn-rounded m-sm" id="add">
<small>ADD EMPLOYEE</small>
</button>
<!--- ADD EMPLOYEES --->
<div class="ibox" id="details" name="details[]">
<div class="ibox-content">
<div class="container">
<div class="row">
<div class="col">
<label class="form-label">Position</label>
<select class="form-control" type="text" name="d" id="d">
<option value="" disabled selected>Select</option>
<option value="ROLE1" name="SPV">ROLE1</option>
<option value="ROLE2" name="REG">ROLE2</option>
</select>
</div>
<div class="col">
<label class="form-label">Name</label>
<input type="text" class="form-control" name="e" id="e">
</div>
<div class="col">
<label class="form-label">TVL</label>
<input type="text" class="form-control" name="f" id="f">
</div>
<div class="col">
<label class="form-label">Start Date</label>
<input type="date" class="form-control" name="g" id="g">
</div>
<div class="col">
<label class="form-label">End Date</label>
<input type="date" class="form-control" name="h" id="h">
</div>
<div class="col">
<label class="form-label">Start Time</label>
<input type="time" class="form-control" name="i" id="i">
</div>
<div class="col">
<label class="form-label">End Time</label>
<input type="time" class="form-control" name="j" id="j">
</div>
<div class="col text-right m-t-lg">
</div>
</div>
</div>
</div>
</div>
<!--- ADD EMPLOYEES END --->
<div class="hr-line-dashed"></div>
<button type="submit" class="btn btn-primary btn-med" name="submit">Submit</button>
</form>
<!-- SCCRIPT-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
JS
main.js
$(document).ready(function(){
var html = ' <div class="ibox" id="details" name="details[i]"> <div class="ibox-content"> <div class="container"> <div class="row"> <div class="col"> <label class="form-label">Position</label> <select class="form-control" type="text" name="d" id="d"> <option value="" disabled selected>Select</option> <option value="SPV" name="SPV">SPV</option> <option value="REG" name="REG">REG</option> </select> </div> <div class="col"> <label class="form-label">Name</label> <input type="text" class="form-control" name="e" id="e"> </div> <div class="col"> <label class="form-label">TVL</label> <input type="text" class="form-control" name="f" id="f"> </div> <div class="col"> <label class="form-label">Start Date</label> <input type="date" class="form-control" name="g" id="g"> </div> <div class="col"> <label class="form-label">End Date</label> <input type="date" class="form-control" name="h" id="h"> </div> <div class="col"> <label class="form-label">Start Time</label> <input type="time" class="form-control" name="i" id="i"> </div> <div class="col"> <label class="form-label">End Time</label> <input type="time" class="form-control" name="j" id="j"> </div> <div class="col text-right m-t-lg"> </div> <div class="col text-right m-t-lg"> <button class="btn btn-sm btn-rounded btn-danger" id="remove"> <i class="fa fa-times"></i> </button> </div></div> </div> </div> </div>'
// Add rows to the form
$(function() {
$('#add').click(function(e) {
$('#details').append(html);
e.preventDefault();
});
// Remove rows from the form
$(this).on('click', '#remove', function(e) {
$(this).closest('#details').remove();
});
});
});
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[id]').each(function(index, value){
var that = $(this),
name = that.attr('id'),
value = that.val();
data[name] = value;
});
$.ajax ({
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
PHP
ajax.inc.php
<?php
include 'form.dbh.php'; {
$jobid = mysqli_real_escape_string($conn,$_POST['a']);
$client = mysqli_real_escape_string($conn,$_POST['b']);
$type = mysqli_real_escape_string($conn,$_POST['c']);
$role = mysqli_real_escape_string($conn,$_POST['d']);
$name = mysqli_real_escape_string($conn,$_POST['e']);
$tvl = mysqli_real_escape_string($conn,$_POST['f']);
$sdate = mysqli_real_escape_string($conn,$_POST['g']);
$edate = mysqli_real_escape_string($conn,$_POST['h']);
$stime = mysqli_real_escape_string($conn,$_POST['i']);
$etime = mysqli_real_escape_string($conn,$_POST['j']);
$sql = "INSERT INTO timesheets(jobid, client, type, role, name, tvl, sdate, edate, stime, etime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, 'ssssssssss', $jobid, $client, $type, $role, $name, $tvl, $sdate, $edate, $stime, $etime);
mysqli_stmt_execute($stmt);
}
header("Location:../index.php?success");
}
?>
Does anyone have an idea? or any suggestions?
Consider the following.
$(function() {
var html = ' <div class="ibox" id="details" name="details[i]"> <div class="ibox-content"> <div class="container"> <div class="row"> <div class="col"> <label class="form-label">Position</label> <select class="form-control" type="text" name="d" id="d"> <option value="" disabled selected>Select</option> <option value="SPV" name="SPV">SPV</option> <option value="REG" name="REG">REG</option> </select> </div> <div class="col"> <label class="form-label">Name</label> <input type="text" class="form-control" name="e" id="e"> </div> <div class="col"> <label class="form-label">TVL</label> <input type="text" class="form-control" name="f" id="f"> </div> <div class="col"> <label class="form-label">Start Date</label> <input type="date" class="form-control" name="g" id="g"> </div> <div class="col"> <label class="form-label">End Date</label> <input type="date" class="form-control" name="h" id="h"> </div> <div class="col"> <label class="form-label">Start Time</label> <input type="time" class="form-control" name="i" id="i"> </div> <div class="col"> <label class="form-label">End Time</label> <input type="time" class="form-control" name="j" id="j"> </div> <div class="col text-right m-t-lg"> </div> <div class="col text-right m-t-lg"> <button class="btn btn-sm btn-rounded btn-danger" id="remove"> <i class="fa fa-times"></i> </button> </div></div> </div> </div> </div>'
$('#add').click(function(e) {
$('#details').append(html);
e.preventDefault();
});
// Remove rows from the form
$(this).on('click', '#remove', function(e) {
$(this).closest('#details').remove();
});
$('form.ajax').on('submit', function(e) {
e.preventDefault();
var that = $(this),
u = that.attr('action'),
t = that.attr('method'),
d = {};
that.find('[id]').each(function(i, el) {
d[$(el).attr("id")] = $(el).val();
});
$.ajax({
url: u,
type: t,
data: d,
success: function(response) {
console.log(response);
}
});
return false;
});
});
This cleans up some of the issues you are seeing. When using .each() you will have an Index and Element, not a Value.
Update
The code above will submit all data based on the form.ajax selector. When you have only one section of details in the form, that is all the data that will be submitted. If you add your HTML, you cause an HTML/JS issue where the ID attributes of the elements are no longer Unique. All IDs must be unique.
Consider ignoring the IDs and make use of name attribute instead. When you gather the data, for d through j, these would need to be Arrays, since these are the items that repeat.
Consider the following.
$(function() {
function getData(f) {
var myData = {
a: $("[name='a']", f).val(),
b: $("[name='b']", f).val(),
c: $("[name='c']", f).val(),
d: [],
e: [],
f: [],
g: [],
h: [],
i: [],
j: []
};
var k, v;
$("[name]", f).each(function(i, el) {
k = $(el).attr("name");
v = $(el).val();
if (i > 2) {
myData[k].push(v);
}
});
console.log(myData);
return myData;
}
$('#add').click(function(e) {
var html = $("#details > .ibox-content:eq(0)").clone(true);
$(".col:last", html).html("<button class='btn btn-sm btn-rounded btn-danger remove' id='remove-" + $(".ibox-content").length + "'> <i class='fa fa-times'></i> </button>");
$(".ibox-content:last").after(html);
e.preventDefault();
});
$("#details").on('click', '.remove', function(e) {
$(this).closest('.ibox-content').remove();
});
$("form.ajax").submit(function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: getData(this),
success: function(response) {
console.log(response);
}
});
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="include/ajax.inc.php" class="ajax">
<h2>Job Details</h2>
<br>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Job ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="a" id="a">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Client</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="b" id="b">
<option value="" disabled selected>Select</option>
<option value="OPTION1">OPTION1</option>
<option value="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type of Work</label>
<div class="col-sm-10">
<select type="text" class="form-control" name="c" id="c">
<option value="" disabled selected>Select</option>
<option value="OPTION1">OPTION1</option>
<option value="OPTION2">OPTION2</option>
</select>
</div>
</div>
<div class="hr-line-dashed"></div>
<h2>Employee Details</h2>
<button class="btn btn-lg btn-primary btn-rounded m-sm" id="add"><small>ADD EMPLOYEE</small></button>
<!--- ADD EMPLOYEES --->
<div id="details" class="ibox">
<div class="ibox-content">
<div class="container">
<div class="row">
<div class="col">
<label class="form-label">Position</label>
<select class="form-control" type="text" name="d" id="d">
<option value="" disabled selected>Select</option>
<option value="ROLE1">ROLE1</option>
<option value="ROLE2">ROLE2</option>
</select>
</div>
<div class="col">
<label class="form-label">Name</label>
<input type="text" class="form-control" name="e" id="e">
</div>
<div class="col">
<label class="form-label">TVL</label>
<input type="text" class="form-control" name="f" id="f">
</div>
<div class="col">
<label class="form-label">Start Date</label>
<input type="date" class="form-control" name="g" id="g">
</div>
<div class="col">
<label class="form-label">End Date</label>
<input type="date" class="form-control" name="h" id="h">
</div>
<div class="col">
<label class="form-label">Start Time</label>
<input type="time" class="form-control" name="i" id="i">
</div>
<div class="col">
<label class="form-label">End Time</label>
<input type="time" class="form-control" name="j" id="j">
</div>
<div class="col text-right m-t-lg">
</div>
</div>
</div>
</div>
</div>
<!--- ADD EMPLOYEES END --->
<div class="hr-line-dashed"></div>
<button type="submit" class="btn btn-primary btn-med">Submit</button>
</form>
You may notice, only specific elements have the name attribute now. DIV elements should not use name and the same goes for OPTION. DIV is not a part of a Form. OPTION is a element part of SELECT which is the parent container and the form element, this should have name.
Your PHP will get a complex payload of data. For example:
{
"a": "2020",
"b": "OPTION1",
"c": "OPTION2",
"d": [
"ROLE1",
"ROLE2"
],
"e": [
"Bob",
"Nancy"
],
"f": [
"1",
"2"
],
"g": [
"2020-10-12",
"2020-10-12"
],
"h": [
"2020-10-16",
"2020-10-16"
],
"i": [
"08:00",
"08:00"
],
"j": [
"12:00",
"12:00"
]
}
You will need to adjust your PHP to handle this new data format.
maybe this question has been asked before, but for my case, an error occurred. I have followed the guidelines here by using jquery.
In my case: When the button is clicked the form changes to enable, but only one second. Then the form changes to be disabled again.
jquery
$(document).ready(function() {
$('.toggleInputs').find('input').prop('disabled', true);
$('.toggleInputs').find('select').prop('disabled', true);
$('.toggleInputs').find('textarea').prop('disabled', true);
});
$('#btnEdit').on('click', function() {
$('.toggleInputs').find('input').prop('disabled', false);
$('.toggleInputs').find('select').prop('disabled', false);
$('.toggleInputs').find('textarea').prop('disabled', false)
});
form html
<form class="toggleInputs" method="post" action="">
<div class="form-group row">
<label class="col-md-3 col-form-label">NIS</label>
<div class="col-md-2">
<input value="<?php echo $nis;?>" name="nisn" placeholder="NIS" class="form-control" required="required" type="text" >
</div>
<div class="col-md-2">
<button id="btnEdit" class="btn btn-danger">UBAH</button>
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label">NAMA LENGKAP</label>
<div class="col-md-5">
<input id="inputSiswa" value="<?php echo $nama_siswa;?>" name="namaSiswa" placeholder="Nama Lengkap" class="form-control" type="text" >
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label">TEMPAT LAHIR</label>
<div class="col-md-3">
<input value="<?php echo $tempatLahir;?>" name="namaSiswa" placeholder="Nama Lengkap" class="form-control" type="text" >
</div>
<label class="col-md-2 col-form-label">TANGGAL LAHIR</label>
<div class="col-md-3">
<input value="<?php echo $tanggalLahir;?>" name="namaSiswa" placeholder="Nama Lengkap" class="form-control" type="text" >
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label">JENIS KELAMIN</label>
<div class="col-md-4">
<select name="jenisKelamin" class="form-control"><option class="form-control" selected>Laki-laki</option>
<option class="form-control" >Perempuan</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label" readonly>ALAMAT</label>
<div class="col-md-5">
<textarea name="infoguru" cols="40" rows="4" class="form-control" ><?php echo $alamatSiswa;?></textarea>
</div>
</div>
</form>
You need to set disabled property to the value disabled I know it is confusing,
$('.toggleInputs input,.toggleInputs select,.toggleInputs textarea')
.prop("disabled","disabled");
and to enable them back, you just remove the property disabled.
$('.toggleInputs input,.toggleInputs select,.toggleInputs textarea')
.removeProp("disabled");
Don't rely on setting the property to true/false because different browsers don't support it that way.
$(document).ready(function(){
$('.toggleInputs input,.toggleInputs select,.toggleInputs textarea').prop("disabled","disabled");
$('#btnEdit').click(function(){
$('.toggleInputs input,.toggleInputs select,.toggleInputs textarea').removeProp("disabled");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form class="toggleInputs" method="post" action="">
<div class="form-group row">
<label class="col-md-3 col-form-label">NIS</label>
<div class="col-md-2">
<input value="<?php echo $nis;?>" name="nisn" placeholder="NIS" class="form-control" required="required" type="text">
</div>
<div class="col-md-2">
<button id="btnEdit" class="btn btn-danger">UBAH</button>
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label">NAMA LENGKAP</label>
<div class="col-md-5">
<input id="inputSiswa" value="<?php echo $nama_siswa;?>" name="namaSiswa" placeholder="Nama Lengkap" class="form-control" type="text">
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label">TEMPAT LAHIR</label>
<div class="col-md-3">
<input value="<?php echo $tempatLahir;?>" name="namaSiswa" placeholder="Nama Lengkap" class="form-control" type="text">
</div>
<label class="col-md-2 col-form-label">TANGGAL LAHIR</label>
<div class="col-md-3">
<input value="<?php echo $tanggalLahir;?>" name="namaSiswa" placeholder="Nama Lengkap" class="form-control" type="text">
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label">JENIS KELAMIN</label>
<div class="col-md-4">
<select name="jenisKelamin" class="form-control">
<option class="form-control" selected>Laki-laki</option>
<option class="form-control">Perempuan</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label" readonly>ALAMAT</label>
<div class="col-md-5">
<textarea name="infoguru" cols="40" rows="4" class="form-control"><?php echo $alamatSiswa;?></textarea>
</div>
</div>
</form>
PS: For some reason, the StackOverflow snippet gives an error when my code runs to re-enable the controls back. But for a moment, you can witness the controls being enabled again, before the error message appears.
May be You have not referenced a jQuery library.
You have to include a line similar to this in your HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
If you referenced jQuery then change priority first add jQuery and then other js.
I am doing a school task and I'm stuck.
I want to gray out the input field based on what is selected in the drop-down menu.
https://jsfiddle.net/xdvan6vf/
function ccGrey() {
if (document.getElementById("creditcard").onchane){
alert("this doesnt work very well")
}
}
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-16 control-label" for="payment-method">Payment Method</label>
<div class="col-md-16">
<select id="payment-method" name="payment-method" class="form-control order-form">
<option value="1">Online</option>
<option value="2">In Store</option>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-16 control-label" for="creditcard">Credit Card Number</label>
<div class="col-md-16">
<input id="creditcard" name="creditcard" type="text" placeholder="CC Number" class="form-control input-md order-form" onclick="ccGrey">
</div>
</div>
I didn't understand what was your purpose but for handling select selected index changing,you must work on onChange on SELECT element not INPUT event like this:
function selectChanged() {
var x = document.getElementById("payment-method").value;
document.getElementById("creditcard").disabled = (x == 1);
}
//Checking for initial run
selectChanged();
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-16 control-label" for="payment-method">Payment Method</label>
<div class="col-md-16">
<select id="payment-method" name="payment-method" class="form-control order-form" onChange="selectChanged()">
<option value="1">Online</option>
<option value="2">In Store</option>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-16 control-label" for="creditcard">Credit Card Number</label>
<div class="col-md-16">
<input id="creditcard" name="creditcard" type="text" placeholder="CC Number" class="form-control input-md order-form">
</div>
</div>
I have a modal where i put my form inside. Now, my problem is, when i click the button of my onclick="regpatient()" button, the required will pop-up but when i look at it in console, the data was submited by a post because of my onlick function. How can i do this?
Here is my modal:
<div class="modal-body">
<form class="form-horizontal" id="frm_patientreg">
<div class="form-group">
<label class="control-label col-sm-3" for="pfname">First Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="pafname" name="pafname" placeholder="First name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pmname">Middle Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="pamname" name="pamname" placeholder="Middle name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="plname">Last Name:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="palname" name="palname" placeholder="Last name" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="paddress">Address:</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="paaddress" name="paaddress" placeholder="Address" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pcontact">Contact #:</label>
<div class="col-sm-7">
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="form-control" id="pacontact" name="pacontact" placeholder="Contact number" maxlength="11" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pbdate">Birthdate:</label>
<div class="col-sm-5">
<div class="input-group date" data-provide="datepicker">
<input type="text" class="form-control" id="pabdate" name="pabdate" placeholder="Birthdate" required>
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="page">Age:</label>
<div class="col-sm-4">
<input type="number" class="form-control" id="paage" name="paage" placeholder="Age" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pheight">Height:</label>
<div class="col-sm-4">
<input type="number" class="form-control" id="paheight" name="paheight" placeholder="Height (cm)" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pweight">Weight:</label>
<div class="col-sm-4">
<input type="number" class="form-control" id="paweight" name="paweight" placeholder="Weight (kg)" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="psex">Sex:</label>
<div class="col-sm-5">
<select class="form-control" id="psex" name="psex">
<option value="0">--- SELECT OPTION ---</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="pmartiastat">Civil Status:</label>
<div class="col-sm-5">
<select class="form-control" id="pmartialstat" name="pmartialstat">
<option value="0">--- SELECT OPTION ---</option>
<option value="Single">Single</option>
<option value="Living common law">Living common law</option>
<option value="Married">Married</option>
<option value="Widowed">Widowed</option>
<option value="Separated">Separated</option>
<option value="Divorced">Divorced</option>
</select>
</div>
</div>
</div><!-- modal-body -->
<div class="modal-footer">
<button value="submit" onclick="regpatient()" class="btn btn-primary">Register Patient</button>
</form>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div><!-- modal-footer -->
</div><!-- modal-content -->
and here is my ajax where it fires when the button in footer of my modal is clicked:
function regpatient() {
var a = $('#psex').val();
var b = $('#pmartialstat').val();
if(a == "0" || b == "0") {
alert("Please select option");
}
else {
$.ajax({
url: siteurl+"sec_myclinic/addpatient",
type: "POST",
data: $('#frm_patientreg').serialize(),
dataType: "JSON",
success: function(data) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
}
If I understand your problem right you want to stop the button's default submit action and only use your onclick script. Try this:
onclick="regpatient(event)"
and
function regpatient(event) {
event.preventDefault();
...
Edit
The required fields are not getting validated by the onclick function. Some checks like this for the required values should help stop the ajax call.
if (!$('#pafname').val()) {
return alert('Please fill in all required fields.');
}
// ajax code here ...
Use this
<button value="button" onclick="regpatient()" class="btn btn-primary">Register Patient</button>
instead of this
<button value="submit" onclick="regpatient()" class="btn btn-primary">Register Patient</button>
My code is below. I am have arrays declared in html input tag name field, title[], first_name[], last_name[], email_address[], twitter_handle[].
I have declared them all arrays for the sake of form cloning that I am doing in .js file.
Now, I am trying to enter the data from form in to database.
I am using the foreach to manage the arrays, I also took a $length variable which will give me the number of form cloning worked.
No matter how many times I clone the form, only the first form gets printed.
Please help.
My code is below:
if(isset($_POST['title']) && isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email_address']) && isset($_POST['twitter_handle'])){
$length=0;
foreach($_POST['title'] as $key=>$value){
$title[$key]=$value;
$length=$length + 1;
echo '$key: '.$key.' '.$length;
//print_r($value);
}
foreach($_POST['first_name'] as $key=>$value){
$first_name[$key]=$value;
}
foreach($_POST['last_name'] as $key=>$value){
$last_name[$key]=$value;
}
foreach($_POST['email_address'] as $key=>$value){
$email_address[$key]=$value;
}
foreach($_POST['twitter_handle'] as $key=>$value){
$twitter_handle[$key]=$value;
}
echo '$lenght : '.$length.' ';
for($i=0;$i<$length;$i++){
print_r($first_name[$i]);
}
}
..................
Just for reference this is my html code:
<form action="<?php $_SERVER['PHP_SELF']?>" method="POST" id="sign-up_area" role="form">
<label class="label_ttl control-label" for="title">Title:</label>
<div class="form-group">
<select class="select_ttl form-control" name="title[]" id="title">
<option value="" selected="selected" disabled="disabled">Select your title</option>
<option value="Dr.">Dr.</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Ms.">Ms.</option>
<option value="Sir">Sir</option>
</select>
</div>
<!-- Text input-->
<div class="form-group">
<label class="label_fn control-label" for="first_name">First name:</label>
<input id="first_name" name="first_name[]" type="text" placeholder="" class="input_fn form-control" required>
<p class="help-block">This field is required.</p>
</div>
<!-- Text input-->
<div class="form-group">
<label class="label_ln control-label" for="last_name">Last name:</label>
<input id="last_name" name="last_name[]" type="text" placeholder="" class="input_ln form-control">
</div>
<div class="form-group">
<label class="label_email control-label" for="email_address">Email:</label>
<input id="email_address" name="email_address[]" type="text" placeholder="example#example.com" class="input_email form-control">
</div>
<!-- Prepended text-->
<label class="label_twt control-label" for="institution">Enter Institution / Organization:</label>
<div class="input-group form-group">
<input id="twitter_handle" name="twitter_handle[]" class="input_twt form-control" placeholder="" type="text">
</div>
<!-- Text input-->
</div><!-- end #entry1 -->
<!-- Button (Double) -->
<p>
<button type="button" id="btnAdd" name="btnAdd" class="btn btn-info">add section</button>
<button type="button" id="btnDel" name="btnDel" class="btn btn-danger">remove section above</button>
</p>
<!-- Button -->
<p>
<button id="submit_button" name="submit_button" class="btn btn-primary">Submit</button>
</p>
</fieldset>
</form>
<?php
if(isset($_POST['title']) && isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email_address']) && isset($_POST['twitter_handle'])){
$length=0;
foreach($_POST['title'] as $key=>$value){
$title[$key]=$value;
$length = $length + 1;
//echo '$key: '.$key.' '.$length;
//print_r($value);
}
foreach($_POST['first_name'] as $key=>$value){
$first_name[$key]=$value;
}
foreach($_POST['last_name'] as $key=>$value){
$last_name[$key]=$value;
}
foreach($_POST['email_address'] as $key=>$value){
$email_address[$key]=$value;
}
foreach($_POST['twitter_handle'] as $key=>$value){
$twitter_handle[$key]=$value;
}
echo '$lenght : '.$length.' ';
for($i=0;$i<$length;$i++){
echo ($first_name[$i])."<br/>";
}
}
?>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<form action="<?php $_SERVER['PHP_SELF']?>" method="POST" id="sign-up_area" role="form">
<div class="form" id="form_1">
<label class="label_ttl control-label" for="title">Title:</label>
<div class="form-group">
<select class="select_ttl form-control" name="title[]" id="title">
<option value="" selected="selected" disabled="disabled">Select your title</option>
<option value="Dr.">Dr.</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Ms.">Ms.</option>
<option value="Sir">Sir</option>
</select>
</div>
<!-- Text input-->
<div class="form-group">
<label class="label_fn control-label" for="first_name">First name:</label>
<input id="first_name" name="first_name[]" type="text" placeholder="" class="input_fn form-control" required>
<p class="help-block">This field is required.</p>
</div>
<!-- Text input-->
<div class="form-group">
<label class="label_ln control-label" for="last_name">Last name:</label>
<input id="last_name" name="last_name[]" type="text" placeholder="" class="input_ln form-control">
</div>
<div class="form-group">
<label class="label_email control-label" for="email_address">Email:</label>
<input id="email_address" name="email_address[]" type="text" placeholder="example#example.com" class="input_email form-control">
</div>
<!-- Prepended text-->
<label class="label_twt control-label" for="institution">Enter Institution / Organization:</label>
<div class="input-group form-group">
<input id="twitter_handle" name="twitter_handle[]" class="input_twt form-control" placeholder="" type="text">
</div>
<!-- Text input-->
</div><!-- end #entry1 -->
<!-- Button (Double) -->
<p>
<button type="button" id="btnAdd" name="btnAdd" class="btn btn-info">add section</button>
<button type="button" id="btnDel" name="btnDel" class="btn btn-danger">remove section above</button>
</p>
<!-- Button -->
<p>
<button id="submit_button" name="submit_button" class="btn btn-primary">Submit</button>
</p>
</fieldset>
</div>
</form>
<script type="text/javascript">
$('#btnAdd').click(function(){
var form_length = $(".form").length;
$('#form_'+form_length).clone().prop({ id: "form_"+parseInt(form_length+1)}).insertAfter('#form_'+form_length);
});
$('#btnDel').click(function(){
var form_length = $(".form").length;
if(form_length == 1){
alert("One form must exist!");
}else{
$('.form').last().remove();
}
});
</script>