I have a form, that uses a php file. The form lets the user:
-input 3 text fields for Title/Price/Description
-Select an image for his product
-Choose a table from the dropdown list (options are the table values)
As you see on my code after the user press the submit button, the browser redirects to another page, saying that "1 records was adder successfully".
I want it to be like after the user clicks the submit button on the form, a (javascript/ajax) messagewill appear letting him know that the records was added successfully.
Sorry for long coding, I think you might need everything.
OPEN TO ANY SUGGESTIONS
form
<div id="addForm">
<div id="formHeading"><h2>Add Product</h2></div><p>
<form id = "additems" action="../cms/insert.php" enctype="multipart/form-data" method="post"/>
<label for="title">Title: </label><input type="text" name="title"/>
<label for="description">Desc: </label><input type="text" name="description"/>
<label for="price">Price: </label><input type="text" name="price" />
<label for="stock">Quan: </label><input type="text" name="stock" />
<p>
<small>Upload your image <input type="file" name="photoimg" id="photoimg" /></small>
<div id='preview'>
</div>
<select name="categories">
<option value="mens">Mens</option>
<option value="baby_books">Baby Books</option>
<option value="comics">Comics</option>
<option value="cooking">Cooking</option>
<option value="games">Games</option>
<option value="garden">Garden</option>
<option value="infants">Infants</option>
<option value="kids">Kids</option>
<option value="moviestv">Movies-TV</option>
<option value="music">Music</option>
<option value="women">Women</option>
</select>
<input type="submit" name="Submit" value="Add new item">
</form>
</div>
insert.php (used on the form)
session_start();
$session_id='1'; //$session id
$path = "../cms/uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$table = $_POST['categories'];
$title = $_POST['title'];
$des = $_POST['description'];
$price = $_POST['price'];
$stock = $_POST['stock'];
$sql="INSERT INTO $table (title, description, price, image, stock)
VALUES
('$title','$des','$price','$path$actual_image_name','$stock')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "<h1>1 record added into the $table table</h1>";
echo '<button onclick="goBack()">Go Back</button>';
with jquery its quite simple:
Just do the following:
1st thing, remove the type="submit" in your input and give it a unique identifier like this:
<input id="submit_form" name="Submit" value="Add new item">
2nd thing, in your javascript file, do:
$(document).ready(function(){
$('input#submit_form').on('click', function() {
$.ajax({
url: 'addnew.php',// TARGET PHP SCRIPT
type: 'post' // HTTP METHOD
data: {
'title' : $('input[name="title"]').val()
},
success: function(data){
alert(data); // WILL SHOW THE MESSAGE THAT YOU SHOWED IN YOUR PHP SCRIPT.
}
});
});
})
3nd thing, in you php file:
Do the same thing but just do:
die("1 record added into the $table table")
Related
I'm trying to populate a dropdown with id='gymnasts' based on the value of another dropdown with id='classes'.
I understand that I must use AJAX, however after following multiple different tutorials I cannot seem to make the second aforementioned dropdown display any options whatsoever.
My code is as follows:
reports.php:
<script>
function getGymnasts(val){
alert('gets');
$.ajax({
type:"POST",
url:"ajax_populate.php",
data: 'classid='+val,
success: function(data){
$("$gymnasts").html(data);
}
});
}
</script>
<form method="post">
<table>
<tr><td>Select Class:</td><td><select id="classes" onChange="getGymnasts(this.value)" placeholder="Select Class" required/>
<?php $classes = mysqli_query($GLOBALS['link'], "SELECT * FROM classes;");
foreach($classes as $class){
echo('
<option value="'.$class['id'].'">'.$class['level'].'</option>
');
}?>
</select></td></tr>
<tr><td>Select Gymnast:</td><td>
<select id="gymnasts" placeholder="Select Gymnast" required/>
</select></td></tr>
<tr><td>Report:</td><td><textarea name="body" cols="60" rows="20" placeholder="Report text" required/></textarea></td></tr>
<tr><td>Progression Grade:</td><td><input type="text" name="progression" placeholder="A" required/></td></tr>
<tr><td>Effort Grade:</td><td><input type="text" name="effort" placeholder="A" required/></td></tr>
<tr><td></td><td><input type="submit" name="saveReport" value="Save"><input type="submit" name="savesendReport" value="Save and Send"></td></tr>
</table>
</form>
ajax_populate.php
include('dbconnect.php');
$classid = $_POST['classid'];
$sql = "SELECT * FROM gymnasts WHERE classid = '$classid'";
$result = mysqli_query($GLOBALS['link'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg ='<option value="'. $row["id"] .'">'. $row["name"] .'</option>';
}
}
else{$msg .="No Gymnasts were found!";}
echo ($msg);
mysqli_close($GLOBALS['link']);
Please help!
You are using wrong selector for gymnasts id, use # instead of $ in your success callback like
success: function(data){
$("#gymnasts").html(data);
// ^ change $ to # here
}
Also, make an option if no result found
else{$msg .="<option>No Gymnasts were found!</option>";}
Fetch selected value from dropdown which is in one form and onClick of the button outside the form send the value to php page
<div class="drpvendorname">
<font style="color: white;">
<label>Distribution Point:</label>
</font>
</div>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option onClick="distribution('.$result['pointshortname'].')" value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form><!--form1 ends here-->
<form action="../customer/form.php"><!--form2 starts here-->
<button class="btn pos7" name="abc" method="GET" style="margin-left:5%;">New Customer</button>
</form><!--form2 ends here-->
<div class="dailybreakupbtn">
<input class="btn" type="submit" id="dailybreakupbutn" name="dailybreakup" value="Enter Daily Breakup" onClick="distribution(<?=$pointname?>)"/>
</div>
<?php
if(isset($pointname)){
?>
<script type="text/javascript">
function distribution(pointname){
var pointname;
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<?php
}
?>
I have tried this sending selected dropdown box value to next page using function name distribution
I ended sending undefined to the next page.
can any one help me sending the selected value to the next page with out putting the button in the <form>
May this will be help you :)
Html code:
<form action= "" method= "post">
<select class="form-control drpvendor" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="'.$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
</form>
JQuery Code:
$(doucment).on('change','.drpvendor',function(){
var data=$(this).attr('selected','selected');
$.ajax({
url: "dailybreakup.php",
data:'query='+ data,
type: "POST",
success: function(data) {
window.location.href='customer/form.php';
}
});
});
Use code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> // please link the path or use cdn
<script type="text/javascript">
function call_me(){
var pointname=document.getElementById("drpvendor").value;
alert(pointname); // comment it after testing
window.location.href="dailybreakup.php?query=" +pointname;
}
</script>
<form>
<select class="form-control" id="drpvendor" name="pointname" required="">
<option selected disabled>Choose distribution point</option>
<?php
$strSQL = "SELECT * FROM point_tbl ORDER BY pointname ASC";
$query = mysqli_query($db, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo '<option value="' .$result['pointshortname'].'">'. $result['pointname'].'</option>';
}
?>
</select>
<input type="button" onclick="call_me()"/>
</form><!--form1 ends here-->
Note : 1) Code is not tested
2) use your select id instead of your_select_id
3) check variable
i need to save selected options values in database . In form, I need to include select options inside input type , Basically i have this code.
<form method="post">
<td>Designer order number </td>
<td>
<div id="ordernumbers">
<select>
<option>Select Order</option>
</select>
</div>
</td>
<input type="text" name="dueDate" value=""/>
<input name="register1" type="submit" id="btnSubmit" value="Update"
onclick="return updatepayment(); "/>
</form>
To include select option inside form , i tried as link1 but did't worked for me.
than i followed below code as in mentioned in link2
<form>
<td>
<div id="ordernumbers">
<input type="text" name="designerorder_id" list="citynames">
<datalist id="citynames">
<option>Select Order</option>
</datalist>
</div>
</td>
</form>
still i am getting Notice: Undefined index: designerorder_id error , but instead of above code , if i use this code : <input type="text" name="designerorder_id" /> i am not getting any error, so i guess i am doing in mistake in putting select inside input in form, please help me for this....
EDit
if (isset($_POST['register1'])) {
$designerorder_id = trim($_POST['designerorder_id']);
$product_id = trim($_POST['product_id']);
$paid_status = password_hash($_POST['paid_status'], PASSWORD_DEFAULT);
$due_date = trim($_POST['due_date']);
$stmt = $reg_user->runQuery("SELECT * FROM order_details");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute();
if ($reg_user->register1($designerorder_id, $product_id, $paid_status, $due_date)) {
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = " updated database";
// $subject = "Confirm updation";
// $reg_user->send_mail($email, $message, $subject);
$msg = "database updated ";
} else {
echo "sorry , Query could no execute...";
}
}
Note : i am requesting downvoter, please inform in comments reason for downvote so that i can correct it....
I am trying to set up my contact form to work with json and ajax, to submit all of the form data to my email and show a success message with the person's name, but everytime I submit the form, event.preventDefault does not work and it shows my contact.php page (Which I am using to process the data and is blank). Here are the 3 files.
HTML
<form id="form" action="contact.php" method="POST">
<input data-name id="name" type="text" name="name" placeholder=" name" required="required"><br>
<input data-email id="email" type="email" name="email" placeholder=" email" required="required"><br>
<select data-projectType id="projectType" name="projectType" required="required">
<option value="" disabled selected>let's talk about</option>
<option value="brand">branding</option>
<option value="web">web design</option>
<option value="app">app design</option>
<option value="print">print design</option>
<option value="dev">development</option>
<option value="multi">multiple services</option>
<option value="hello">just saying hello!</option>
</select>
<br>
<label for="budget"></label>
<select data-budget id="budget" name="budget" required="required">
<option value="" disabled selected>project budget</option>
<option value="none">none</option>
<option value="> $100">less than $100</option>
<option value="$100-$400">$100 - $400</option>
<option value="$400-$700">$400 - $700</option>
<option value="$700-$100">$700 - $1000</option>
<option value="Negotiate">let's negotiate</option>
<option value="IDK">i don't know</option>
</select>
<br>
<input data-details id="details" type="text" name="details" placeholder=" project details" required="required"><br>
<div class=".grid_4">
<input type="submit" input class="MainCTAContact" input value="DROP ME A LINE"></input>
</form>
PHP
$name = $_POST['name'];
$email = $_POST['email'];
$projectType = $_POST['projectType'];
$budget = $_POST['budget'];
$details =$_POST['details'];
//email address settings
$to = "heathersheridanodesk#yahoo.com";
$headers = "From: $email";
$subject= "I'd like to discuss $projectType";
$message = "Name: $name\nEmail: $email\nProject Type: $projectType\nBudget: $budget\nDetails: $details";
if ( $name == "")
{
echo 'Please tell me your name.';
$result = "Please tell me your name.";
}
else if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email))
{
echo 'Please enter a valid email address.';
$result = "Please enter a valid email address.";
}
else if( $projectType == "")
{
echo 'Please select project type';
$result = "Please select project type";
}
else if( $budget == "")
{
echo 'Please select your budget.';
$result = "Please select your budget.";
}
else if ( strlen($details) < 10 )
{
echo ' Please write at least 10 characters.';
$result = "Please write at least 10 characters.";
}
else
{
mail($to, $subject, $message, $headers);
}
}
?>
JS
$(document).ready(function() {
$('#form').submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax( {
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: form.serialize(),
url: "contact.php",
success: function(result) {
form.remove();
var msg = $("<p></p>");
msg.append("Thank you" + data["name"] + ", I'll be in touch soon.")
$('.sent').html(msg).fadeIn();
},
});
how do I make this work?
Okay so I took the time to reformat your stuff a little bit with some explanations in the comments of the code, hopefully this helps you out, but you should definitely look into to web tutorials on AJAX and form processing.
FORM
<form id="form" action="contact.php" method="POST">
<input id="name" type="text" name="name" placeholder=" name" required><br>
<input id="email" type="email" name="email" placeholder=" email" required><br>
<select id="projectType" name="projectType" required>
<option value="" selected>let's talk about</option>
<option value="brand">branding</option>
<option value="web">web design</option>
<option value="app">app design</option>
<option value="print">print design</option>
<option value="dev">development</option>
<option value="multi">multiple services</option>
<option value="hello">just saying hello!</option>
</select>
<br>
<label for="budget"></label>
<select id="budget" name="budget" required="required">
<option value="" selected>project budget</option>
<option value="none">none</option>
<option value="> $100">less than $100</option>
<option value="$100-$400">$100 - $400</option>
<option value="$400-$700">$400 - $700</option>
<option value="$700-$100">$700 - $1000</option>
<option value="Negotiate">let's negotiate</option>
<option value="IDK">i don't know</option>
</select>
<br>
<textarea id='details' rows='5'><textarea><br>
<button type='submit' class='MainCTAContact'>Drop me a line</button>
</form>
JAVASCRIPT
$(document).ready(function() {
$('#form').submit(function(e) {
e.preventDefault();
//create a new object here
var data = {
name : $('#name', this).val(),
email : $('#email', this).val(),
projectType : $('#projectType', this).val(),
budget : $('#budget', this).val(),
details : $('#details', this).val()
};
$.ajax({
type: 'POST',
dataType: 'json',
data: data,
url: "/contact.php",
success: function(data) {
if(!data.errors){
$('#errors').hide();
$('#form')[0].reset(); //add this just to clear out the user submitted data
$('#form').hthml(data.message)); //rather than remove this just sets its visibility to none. Remove complete destroys the element which might not be desierable in all cases
}else{
$('#form').before('<p id='errors' style='color: #ff0000;'>'+data.errorMessage+'</p>');
}
}
});
});
});
Finally your PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$projectType = $_POST['projectType'];
$budget = $_POST['budget'];
$details =$_POST['details'];
//add in a blank error message the error count, and the return array
$errors = 0;
$errorMessage = "";
$resposne = array();
$response['errors'] = false; //initialize the response boolean
if (empty($name)){
$errorMessage .= 'Please tell me your name<br>';
}
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email)){
$errorMessage .= 'Please enter a valid email address<br>';
}
if(empty($projectType)){
$errorMessage .= 'Please select project type<br>';
}
if(empty($budget)){
$errorMessage .= 'Please select your budget.<br>';
}
if(empty($details) || strlen($details) < 10){
$errorMessage .= "Please make sure your message is at least 10 characters long<br>";
}
if(!empty($errorMessage)){
$response['errors'] = true;
$response['errorMessage'] = "There were some errors when processing your form <br> $errorMessage";
}else{
$to = "heathersheridanodesk#yahoo.com";
$headers = "From: $email";
$subject= "I'd like to discuss $projectType";
$message = "Name: $name\nEmail: $email\nProject Type: $projectType\nBudget: $budget\nDetails: $details";
mail($to, $subject, $message, $headers);
$response['message'] = "Thank you, $name, I will be in touch with you soon!";
}
echo json_encode($resposne) // this is needed inorder for the ajax to retrieve the data from the server
?>
Pretty much what you need to remember is the following:
form controls i.e. inputs, textareas, etc only need a minimum amount of information, type and id.
most form control options like disabled, require, readonly, can be put in just using those keywords, so you don't need to do things like disabled='disabled'
when using the $.ajax in jquery you only need in this situation, url, type, data, dataType, success
in the PHP organize your data cleanly so that the code is easier to read later on
when working with ajax you must store everything in a single response array, and echo that encoded array back to the server on completion, other wise you will not be able to retrieve that data.
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*/
}