Send data to PHP Class and post in in SQL database - javascript

I am quite new in PHP and all web development. I am wondering if someone could help me with data flow. I am trying to send form data to a PHP file and then call the function from the class to send data to the sql database. Right now, I don't have any PHP extensions in VS Code so I could debug it and see what is not working. And ofcourse in DOM there is only JS file and PHP which holds HTML code.
This is my code in JavaScript where it takes all user given data and sends it to php. But in form it consists of three static inputs, and then there is a switcher, which displays a user defined view.
`
//Function check for correct input with .value() call
//If it returns 'true' it proceedss with further validation of additional fields that change dynamically.
//When all fields have passed validation function begins to POST FormData to PHP file for backend work.
if(validate.test(sku) && validate.test(name) && validatePrice.test(price)){
if(validateAdditional(this.switcher)){
let xml = new XMLHttpRequest();
xml.open("POST", "./backend/product.php", true);
xml.onload = () => {
if(xml.readyState == 4 && xml.status == 200){
let response = xml.response;
alert(response);
form.reset()
history.back();
}
};
let formData = new FormData(form);
xml.send(formData);
}
}else{
alert("Please check if there is not any spaces or special characters added");
}
}
Then I created a class that will hold all of the network calls to post/read/edit/delete data from the sql database.
class DatabaseCalls{
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "scandiweb";
public function insertData($dataQuery){
$connection = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if(!$connection){
return die("Connection failed" . $connection->connect_error);
}
if($connection->query($dataQuery)){
return "Done";
}else{
echo "Error: " . $dataQuery . "<br>" . $connection->connect_error;
}
$connection->close();
}
}
And then where there are model call network functions to send it to sql. JS file post data to models file. And then procedurally create the Product object and call the first function where I populate the input data.
<?php
include("netowking.php");
$sku = $_POST['sku'];
$name = $_POST['name'];
$price = $_POST['price'];
$memory = $_POST['dvd-memory'];
$dvdProduct = new Product($sku, $name, $price, $memory);
echo $dvdProduct->insertQuery();
class Product extends DatabaseCalls{
private $sku;
private $name;
private $price;
private $memory;
public function __construct($sku, $name, $price, $memory){
$this->sku = $sku;
$this->name = $name;
$this->price = $price;
$this->memory = $memory;
}
public function insertQuery(){
$sql = "INSERT INTO dvd (SKU, Name, Price, Memory)
VALUES ('$sku', '$name', '$price', '$memory')";
$response = $this->insertData($sql);
return $response;
}
}
And for context I will all also HTML code.
<form class="input" name="input">
<div>
<label for="sku">SKU:</label>
<input id="sku" type="text" name="sku" placeholder="#SKU">
</div>
<div>
<label for="name">Name:</label>
<input id="name" type="text" name="name" placeholder="#name">
</div>
<div>
<label for="price">Price ($):</label>
<input id="price" type="text" name="price" placeholder="#price">
</div>
<div class="switcher">
<h3>Type Switcher</h3>
<select name="select" id="select">
<option selected disabled>Choose a type</option>
<option value="dvd">DVD</option>
<option value="furniture">Furniture</option>
<option value="book">Book</option>
</select>
</div>
<div class="switchContent">
<div class="dvd-mem", id="dvd">
<p>DVD-disc</p>
<label for="dvd-memory">Size(MB):</label>
<input id="dvd-memory" type="text" name="dvd-memory" placeholder="Please enter MB amount here">
<p>Please enter amount of disc memory in MB.</p>
</div>
<div class="furniture" id="furniture">
<p>Furniture</p>
<div>
<label for="height">Height(CM):</label>
<input id="height" type="text" name="height" placeholder="Enter height in here">
</div>
<div>
<label for="width">Width(CM):</label>
<input id="width" type="text" name="width" placeholder="Enter width in here">
</div>
<div>
<label for="lenght">Height(CM):</label>
<input id="lenght" type="text" name="lenght" placeholder="Enter lenght in here">
</div>
<p>Please enter all dimensions of furniture</p>
</div>
<div class="book" id="book">
<p>Book</p>
<label for="weight">Weight(KG):</label>
<input id="weight" type="text" name="weight" placeholder="Please enter weight in KG">
<p>Please enter weight of book</p>
</div>
</div>
</form>

Related

Trouble with getting data from newly created input fields via Add button into database

So the problem is that the database is accepting only the data entered into the first input field.
PHP
<form class = "spendings" method ="POST" action="InsertToDatabase.php">
<div id="numbering">ITEM 1: </div>
<div class="entry">
<label for= "item" class= "items">Item Name: </label>
<input type="text" name="enterItems" id="enterItems" placeholder = "Please Enter The Item Name"></input>
<label for ="price" class="price"> Price: </label>
<input type = "number" name="enterPrice" id="enterPrice" placeholder="Please Enter The Price" />
</div>
<div id="add">
</div>
<input type ="button" id = "more_items" onclick ="addMore()" value = "Add More">
<button type = "submit" class="submit">Submit</button>
</form>
insertToDatabase.php
<?php
$host = "localhost";
$user= "root";
$password= '';
$conn = mysql_connect($host, $user, '') or die("Could not connect");
$select = mysql_select_db("sharjeel",$conn);
$enterNames = mysql_real_escape_string($_POST['enterItems']);
$enterNumbers = mysql_real_escape_string($_POST['enterPrice']);
if($enterNames != '')
$msql="INSERT INTO `spendings` (itemName, Price) VALUES ('$enterNames', '$enterNumbers')";
$result= mysql_query( $msql, $conn);
mysql_close($conn);
?>
and the JS
var item =1;
function addMore(){
item++;
var addDiv= document.getElementById("add");
var divTest = document.createElement("form");
divTest.innerHTML=' <form class = "spendings" method ="POST" action="insertToDatabase.php"><div id="numbering">ITEM '+ item + ':</div><div class="entry"><label for= "item" class= "items">Item Name: </label> <input type="text" class="enterItems" placeholder = "Please Enter The Item Name" /><label for ="price" class="price"> Price: </label><input type = "number" class="enterPrice" placeholder= "Please Enter The Price" /></div></form>';
addDiv.appendChild(divTest);
}//end addMore
The first input field add the data into the database; however, after clicking "Add more" button and entering data into the newly created field the data is not entered intor the database.
Thank you for you reply
change name attribute to array from string i.er name="enterItems[]" and name="enterPrice[]" and use loop on the php to insert data into the database.
You also dont need to clone whole form again. Just clone content inside the form.
Your Error is in the If statement , you forgot to use '{}'
and regardless of the inserting only one value into your database, just add into your database table spendings id that holds unique identifier or primary key.
it should look like this.
this should be your insertToDatabase.php
<?php
$conn = mysqli_connect("localhost", "root", "", "Your database");
$enterNames =$_POST['enterItems'];
$enterNumbers = $_POST['enterPrice'];
if($enterNames != ''){
$msql= "INSERT INTO `spendings` (itemName, Price) VALUES ('$enterNames', '$enterNumbers')";
$result= mysqli_query( $conn,$msql);
header('Location: index.php');
}
mysqli_close($conn);
?>
I've made some of the changes to your code just to make you understand how can you achieve what you want.
HTML
<div class="entry">
<label for= "item" class= "items">Item Name: </label>
<input type="text" name="enterItems[]" id="enterItems" placeholder = "Please Enter The Item Name"></input>
<label for ="price" class="price"> Price: </label>
<input type = "number" name="enterPrice[]" id="enterPrice" placeholder="Please Enter The Price" />
</div>
<div id="add">
</div>
<input type ="button" id = "more_items" onclick ="addMore()" value = "Add More">
<button type = "submit" class="submit">Submit</button>
</form>
JS
<script type="text/javascript">
var item =1;
function addMore(){
item++;
var addDiv= document.getElementById("add");
var divTest= document.getElementsByClassName('entry')[0],
clone = divTest.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = item;
addDiv.appendChild(clone);
}
</script>
PHP
<?php
if(isset($_POST['enterItems'])){
for ($i=0; $i < sizeof($_POST['enterItems']); $i++) { // this is the loop i was talking about
// you will need to create and execute your mysql command here in order to insert all the records into the database.
echo $_POST['enterItems'][$i];
echo $_POST['enterPrice'][$i];
}
}
?>

Entered Fields should not be cleared with alert box is displayed in php

I am trying to display a message if the amount entered greater than 5000 alert box or echo messsage "Enter a pan card no" as to be displayed when I click on submit button. In my code Message gets displayed but all the fields which data has been already entered gets cleared. I dont want the data which is entered to get cleared.
Here is the code.
<?php
include_once "db.php";
if(isset($_POST['submit'])) {
$amount = mysql_real_escape_string($_POST["amount"]);
$firstname=mysql_real_escape_string($_POST["firstname"]);
$phone=mysql_real_escape_string($_POST["phone"]);
$address=mysql_real_escape_string(stripslashes($_POST["address"]));
$pan=mysql_real_escape_string(stripslashes($_POST["pan"]));
$query= mysql_query("INSERT INTO payment (amount,selector1,firstname,lastname,email,phone,address,country,state,pan)VALUES('$amount','$selector1','$firstname','$lastname','$email','$phone','$address','$country','$state','$pan') ") or die(mysql_error());
if($amount>="5000")
{
echo "Enter Pan Card No";
}
else {
$id=mysql_insert_id();
$_SESSION['sess_user'] = $id;
$_SESSION['lastname'] = $lastname;
$_SESSION['address']=$address;
header("Location:successreg.php");
}
}
?>
<form action="" method="post" name="payment">
<div class="w3l-user">
<input type="text" name="amount" placeholder="₹ My Contribution" required="">
</div>
<input type="text" name="firstname" placeholder="Firstname" required="">
<input type="text" name="pan" placeholder="Pan Card No" >
</div>
<div class="btn">
<input type="submit" name="submit" value="REGISTER"/>
</div>
</div>
<div class="clear"></div>
</form>
</div>
</div>
In order to show values, after for submission you should get values from $_POST and use them in input values:
$firstname = '';
if(isset($_POST['submit'])) {
// write below line after `if`
$firstname = $_POST['firstname'];
Now, change your HTML to:
<input type="text" name="firstname" placeholder="Firstname" required="" value="<?php echo $firstname; ?>">
For Radio buttons:
$firstRadio = $secondRadio = '';
if(isset($_POST['submit'])) {
// if first radio is selected which you will know from $_POST['firstRadio']
$firstRadio = 'selected';
And in HTML:
<input type='radio' <?php echo $firstRadio;?> value=1 name='firstRadio' />

Disabling Submit button on form in Chrome

How can I disable the Submit button on a form after its clicked? The goal is prevent users from hitting the browser's back button and resubmitting the same details twice, as well as clicking it twice in quick succession if the POST method is slower than expected. I found some ideas here which seem to work fine in Safari, but in Chrome it looks like my onSubmit form function doesn't fire as the button's caption doesn't change and the button stays enabled. I need a simple JS/php method for achieving this.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<title>Entry Form</title>
<body>
<h2 align="center">Entry Form - <?php echo date("Y");?></h2>
<form id="entryForm" method="post" action="formSubmit.php" onsubmit="return checkForm(this);">
<h3>Entrant Info</h3>
<div><input name="fName" type="text" size="80" placeholder="Given name(s)" required> <strong>*</strong></div>
<br>
<div><input name="lName" type="text" size="80" placeholder="Last name" required> <strong>*</strong></div>
<br>
<div><input type="tel" name="phone" size="25" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="Phone number (123-456-7890)"></div>
<br>
<div><input type="email" name="email" size="80" placeholder="Email"></div>
<br>
<h3>Model Info</h3>
<div><input type="text" name="modelName" size="80" placeholder="Title or name of entry" required> <strong>*</strong></div>
<br>
<div><textarea name="remarks" rows="10" cols="80" placeholder="Remarks"></textarea></div>
<br>
<select name="category" size="1" required>
<!--<option value="0">--Please Select --</option>-->
<option disabled selected value> -- Select a category -- </option>
<?php
// Use mySQL Procedurel
// mySQL server connection info
$servername = "localhost";
$username = "xxxx";
$password = "yyyy";
$dbname = "zzzz";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, Category FROM category WHERE Year = YEAR(CURDATE()) ORDER BY Category";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { ?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['Category']; ?></option>
<?php
}
}
else {
echo "No results";
}
mysqli_close($conn);
?>
</select> <strong>*</strong>
<br>
<br>
<div>SECURED to base?
<input id="securedRadioYes" type="radio" name="securedToBase" value="Yes">Yes
<input id="securedRadioNo" type="radio" name="securedToBase" value="No" checked>No</div>
<div>
<h4>Terms and Conditions</h4>
I understand that the terms.</div>
<br>
<br>
<div>I accept the Terms and Conditions:
<input id="acceptAgrmt" name="acceptAgrmt" type="checkbox" value="" required> <strong>*</strong></div>
<br>
<br>
<div>
<input type="submit" name="mysubmit" value="Submit Entry">
<input type="button" value="Reset Form" onclick="resetForm(this.form);">
</div>
</form>
<script type="text/javascript">
function checkForm(form) // Submit button clicked
{
//
// check form input values
//
// User has to check Terms and Conditions
if(!form.acceptAgrmt.checked) {
alert("Please indicate that you accept the Terms and Conditions");
form.acceptAgrmt.focus();
return false;
}
else {
// do other field validations here?
form.mysubmit.disabled = true;
form.mysubmit.value = "Please wait...";
return true;
}
}
function resetForm(form) // Reset button clicked
{
form.mysubmit.disabled = false;
form.mysubmit.value = "Submit Entry";
// Clear out all user entries
form.acceptAgrmt.checked=false;
document.getElementById('securedRadioNo').checked = true;
form.category.value="";
form.remarks.value="";
form.modelName.value="";
//form.email.value="";
//form.phone.value="";
//form.lName.value="";
//form.fName.value="";
}
</script>
</body>
</html>
One way you could deal with this is just to hide or disable pointer-actions on the form after it's clicked -- modify the hidden attribute of the form element, or set form.style.pointerActions = "none".

Insert value in DB with form on a barcode scanner

I have a Datalogic Barcode Scanner Falcon 4410. I have a html form on it to add products into a database.
Here is my simple form :
<form id="formprod" class="form-horizontal" method="post" action="url">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Référence</label>
<div class="col-md-4">
<input id="textinput" name="reference" type="text" placeholder="placeholder" class="form-control input-md">
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<div class="col-md-8">
<input type="submit" id="button1id" name="submit" value="OK" class="btn btn-success"/>
<input type="reset" id="button2id" name="button2id" value="RESET" class="btn btn-danger"/>
</div>
</div>
</fieldset>
</form>
So, in the barcode scanner if I open my html page, write with virtual keyboard in input and submit with submit button: it works.
But if I'm scanning a barcode, form is automatically submitted, record is saved but reference field is empty in DB.
My PHP code :
<?php
if(isset($_POST["reference"])){
$hostname='****';
$username='****';
$password='*****';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=name",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO product (reference)
VALUES ('".$_POST["reference"]."')";
if ($dbh->query($sql)) {
echo 'Done!';
}
else{
echo 'Error!';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Do you have an idea?
Thanks.
PS : It's not optimized for SQL injection for example, it will be done when record will work
EDIT : WORK AFTER A REBOOT.
Most barcode scanners I've used in libraries send a carriage return following the data they've scanned. There is often a way to declare that you don't want a CR in the scanner's settings. Check the manufacturer's website.

Sending a dynamic form via jquery ajax php

I have a pet registration form where people can add a new pet.
People will click the add pet button and jquery clones the pet portion of the form and changes the id to #pet-2, another, #pet-3 and so on.
After fruitless web searching, I now need to know how to send this via php and ajax.
I have already created an ajax function for my contact forms as well as have php code to send the contact forms so would, ideally, want to modify that code in a separate file to handle the register pet also.
Here is the fiddle: http://jsfiddle.net/zsxe44c8/
Here is the code for the add pet form:
<form id="register-pet-form" data-quantity="1">
<fieldset id="practiceField" class="row">
<div class="col-md-6 push-md-6">
<h3>Practice</h3>
<select name="practice">
<option value="">Value 1</option>
<option value="">Value 2</option>
</select>
</div>
</fieldset>
<!--/#practiceField-->
<fieldset id="ownerDetails" class="row">
<div class="col-md-6">
<h3>Your details</h3>
<select name="title">
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Ms">Ms</option>
<option value="Dr">Dr</option>
<option value="Prof">Prof</option>
</select>
<input name="fname" type="text" placeholder="First Name">
<input name="lname" type="text" placeholder="Last Name">
<input name="number" type="text" placeholder="Contact Number">
<input name="email" type="text" placeholder="Email Address">
</div>
<div class="col-md-6">
<h3>Your Address</h3>
<input name="address1" type="text" placeholder="Address 1">
<input name="address2" type="text" placeholder="Address 2">
<input name="address3" type="text" placeholder="Address 3">
<input name="postcode" type="text" placeholder="Postcode">
</div>
</fieldset>
<!--/#ownerDetails-->
<fieldset id="pet-1" class="row">
<div class="col-md-12">
<h3>Pet Details</h3>
</div>
<div class="col-md-6">
<input name="pet-name" type="text" placeholder="Pet Name">
<input name="pet-breed" type="text" placeholder="Pet Breed">
<input name="pet-age" type="text" placeholder="Age of pet">
</div>
<div class="col-md-6">
<select name="petGender">
<option value="Female">Female</option>
<option value="Male">Male</option>
</select>
<select name="petType">
<option value="Dog">Dog</option>
<option value="Cat">Cat</option>
<option value="Rabbit">Rabbit</option>
<option value="Gerbil">Gerbil</option>
<option value="Guinea Pig">Guinea Pig</option>
<option value="Hamster">Hamster</option>
<option value="Mouse">Mouse</option>
<option value="Rat">Rat</option>
<option value="Chinchilla">Chinchilla</option>
<option value="Other">Other</option>
</select>
</div>
<div class="col-md-12">
<input name="pet-desc" type="text" placeholder="Pet Description">
<textarea name="additional-comments" placeholder="Additional Comments"></textarea>
</div>
</fieldset>
<!--#petDetails-->
<div id="form-tools" class="row">
<div class="col-md-6">
<a class="add-pet" href="#">Add another pet</a>
</div>
<div class="col-md-6 right">
<input type="submit" value="Submit">
</div>
</div>
<!--/#form-tools-->
</form>
Here is the jQuery code for the add pet form:
function registerPet() {
function addPetRegistrationForm() {
var container = $('#register-pet-form'),
lastForm = $('#register-pet-form fieldset:last-of-type'),
currentForm = $('#pet-1'),
newForm = currentForm.clone(),
currentVal = parseInt(container.attr('data-quantity'), 10),
newVal = currentVal + 1;
$('h3', newForm).after('<a data-id="' + newVal + '" class="js-remove-pet remove-pet" href="#">Remove this pet</a>');
$('input, select', newForm).each(function () {
var newId = this.id.substring(0, this.id.length - 1) + newVal;
$(this).prev().attr('for', newId);
this.name = this.id = newId;
});
lastForm.after(newForm.attr('id', 'pet-' + newVal));
container.attr('data-quantity', newVal);
}
function removePetRegistrationForm(target) {
$('#pet-' + target).remove();
}
function handleRegisterPet() {
if($('#pet-1').length) {
$('#pet-1').addClass('ispet');
$('#pet-1 *[name]').each(function(){
$(this).attr('name',$(this).attr('name') + '[]');
});
var newBlock = $('#pet-1').html();
$('#pet-1').after('Add another pet');
$('.add-pet').on('click',function() {
var count = $('.ispet').length + 1;
$('.ispet').last().after('<fieldset id="pet-'+ count +'" class="ispet">' + newBlock + '</fieldset>');
return false;
});
}
}
$('.add-pet').on('click', function () {
addPetRegistrationForm();
return false;
});
$('#register-pet-form').on('click', '.js-remove-pet', function () {
removePetRegistrationForm($(this).attr('data-id'));
return false;
});
}
Now here is the code for the ajax contact form that is working and I wish to modify for the add pet form:
function ajaxForm(formID) {
var form = $(formID);
var formMessages = $('#form-messages');
$(formMessages).hide();
$(form).submit(function(event) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function() {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(form).hide();
$('#fname').val('');
$('#lname').val('');
$('#email').val('');
$('#phone').val('');
$('#message').val('');
$(formMessages).html(
'<div class="alert alert-success" role="alert"><i class="fa fa-check"></i> <strong>Your message has been sent successfully</strong></div>'
).fadeIn();
})
.fail(function() {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
}
function practiceOneContact() {
ajaxForm('#practice-1-contact-form');
}
function practiceTwoContact() {
ajaxForm('#practice-2-contact-form');
}
function practiceThreeContact() {
ajaxForm('#practice-3-contact-form');
}
function practiceFourContact() {
ajaxForm('#practice-4-contact-form');
}
And finally, the PHP code for the contact form handler that I wish to modify to allow for dynamic pets from the add pet form:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$fname = strip_tags(trim($_POST["fname"]));
$fname = str_replace(array("\r","\n"),array(" "," "),$fname);
$lname = strip_tags(trim($_POST["lname"]));
$lname = str_replace(array("\r","\n"),array(" "," "),$lname);
$phone = strip_tags(trim($_POST["phone"]));
$phone = str_replace(array("\r","\n"),array(" "," "),$phone);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
$sendTo = strip_tags(trim($_POST["sendTo"]));
$practice = trim($_POST["practice"]);
echo 'field editing done';
// Check that data was sent to the mailer.
if ( empty($fname) OR empty($lname) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = $sendTo;
// Set the email subject.
$subject = "New contact from $fname $lname";
// Build the email content.
$email_content = "Practice Name: $practice\n";
$email_content .= "First Name: $fname\n";
$email_content .= "Last Name: $lname\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $fname $lname <$email>";
echo 'section build done';
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
echo "There was a problem with your submission, please try again.";
}
The URLS for this project are as follows: http://cvs.dev.dannycheeseman.me/base/about-us/register-your-pets/
Register Pet: http://cvs.dev.dannycheeseman.me/base/contact-us/
Thank you for your time.
Seems like you want to post the whole form, including the input files generated dynamically.
if so, then you will want to see into using array of input.
<form method="POST" action="whereever.php>
<input type="text" name="name[]" value="Dog" />
<input type="text" name="name[]" value="Cat" />
<input type="text" name="name[]" value="Snake" />
</form>
When the form is sent (whether by basic or AJAX), the PHP script can read the input as an array
<?php
echo $_POST['name'][0]."<br>";
echo $_POST['name'][1]."<br>";
echo $_POST['name'][2]."<br>";
?>
above script will output
Dog
Cat
Snake
This can be applied to all input.
Does this help?
Addition
So in your case, you can do it like this:
<form>
<section>
Pet # 1
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>
<section>
Pet # 2
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>
<section>
Pet # 3
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>
</form>
To read the POST dynamically
foreach($_POST["name"] as $key => $value)
{
echo $value;
/*or if you want to loop while accessing other fields too, you can do this*/
echo "<br>".$_POST["name"][$key];
echo "<br>".$_POST["lastname"][$key];
/*this way you can access the other fields with the same <section> as well, just make sure you do not mess with the input placement*/
}

Categories