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*/
}
Related
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>
I should solve a problem with a contact form and I don't know where to put my hands anymore.
I have a form in HTML, then a validation in JS and finally an email sending in PHP.
The form data are: Name, Clinic, Email, Phone, Address and Valutation.
In the email I receive the data are:
Name: name entered in the form
Email: email entered in the form
Clinic: undefined
Phone: undefined
Address: undefined
Valutation: undefined
This is the code (HTML + JS):
// JavaScript Document
$(document).ready(function() {
"use strict";
$(".contact-form").submit(function(e) {
e.preventDefault();
var name = $(".name");
var email = $(".email");
var clinic = $(".clinic");
var phone = $(".phone");
var address = $(".address");
var valutation = $(".valutation");
var subject = $(".subject");
var msg = $(".message");
var flag = false;
if (name.val() == "") {
name.closest(".form-control").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".form-control").removeClass("error").addClass("success");
}
if (email.val() == "") {
email.closest(".form-control").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".form-control").removeClass("error").addClass("success");
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&subject=" + subject.val() + "&msg=" + msg.val() + "&clinic=" + clinic.val() + "&phone=" + phone.val() + "&address=" + address.val() + "&valutation=" + valutation.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "php/contactForm.php",
cache: false,
success: function(d) {
$(".form-control").removeClass("success");
if (d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="#48af4b">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="#ff5607">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").on('click', function() {
$(".form-control").removeClass("success").removeClass("error");
});
})
<div class="row justify-content-center">
<div class="col-lg-10 col-xl-8">
<div class="form-holder">
<form class="row contact-form" method="POST" action="php/contactForm.php" id="contactForm">
<!-- Form Select -->
<div class="col-md-12 input-subject">
<p class="p-lg">This question is about: </p>
<span>How satisfied are you with the service that Lab offers? </span>
<select class="form-select subject" aria-label="Default select example" name="valutation">
<option>Very unsatisfied</option>
<option>Unsatisfied</option>
<option>Satisfied</option>
<option>Very satisfied</option>
<option selected>I don't have an opinion</option>
</select>
</div>
<!-- Contact Form Input -->
<div class="col-md-12">
<p class="p-lg">Your Name: </p>
<span>Please enter your Dentist Name: </span>
<input type="text" name="name" class="form-control name" placeholder="Your Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Clinic Name: </p>
<span>Please enter your Clinic Name: </span>
<input type="text" name="clinic" class="form-control name" placeholder="Clinic Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Your Email Address: </p>
<span>Please carefully check your email address for accuracy</span>
<input type="text" name="email" class="form-control email" placeholder="Email Address*">
</div>
<div class="col-md-12">
<p class="p-lg">Phone Number: </p>
<span>Please enter your/clinic phone number: </span>
<input type="text" name="phone" class="form-control name" placeholder="Phone Number*">
</div>
<div class="col-md-12">
<p class="p-lg">Address: </p>
<span>Please enter Clinic Address: </span>
<input type="text" name="address" class="form-control name" placeholder="Address*">
</div>
<!-- Contact Form Button -->
<div class="col-md-12 mt-15 form-btn text-right">
<button type="submit" class="btn btn-skyblue tra-grey-hover submit">Submit Request</button>
</div>
<!-- Contact Form Message -->
<div class="col-lg-12 contact-form-msg">
<span class="loading"></span>
</div>
</form>
</div>
</div>
</div>
And this is the PHP code:
<?php
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$clinic = $_REQUEST["clinic"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$valutation = $_REQUEST["valutation"];
$to = "myemail#email.com";
if (isset($email) && isset($name)) {
$email_subject = "Request to access to the Price List";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: $name<br/> Email: $email <br/> Clinic: $clinic <br/> Phone: $phone <br/> Address: $address <br/> Valutation: $valutation";
$mail = mail($to, $email_subject, $msg, $headers);
if ($mail) {
echo 'success';
} else {
echo 'failed';
}
}
?>
Your issue is your selectors. You only use classes name and email for all your inputs.
<input type="text" name="phone" class="form-control name" ...>
should actually be:
<input type="text" name="phone" class="form-control phone" ...>
and so on for all the other inputs. Change your selectors to the appropriate classNames.
Also, never just use i.e: $(".name");, $(".email"); etc. as your selectors. As you know already $(".name"); will get every class="name" in your document. Same goes for all the other selectors. Instead, use the second argument (ParentElement) that will limit the search only to the children elements of the provided parent:
var name = $(".name", this);
or rather, use attribute selectors like:
var clinic = $(`[name="clinic"]`, this);
IMPORTANT NOTE about validation:
never trust the client.
JS validation should be used minimally, just as a UX tool to help, inform the user about basic errors/typos. The real validation, as well as all the related error responses, should be handled on the backend side.
Currently your PHP seems quite open to XSS attacks.
You don't need a HTML <form> in order to send data to the server. All it takes to an attacker is to find your route/path (usually exposed via the form's action attribute), take a look at the names in the source and manually construct a HTTP request, and send dangerous arbitrary data to your server. Just so you keep in mind.
I have a form that I am trying to process payments for by following this example (https://gist.github.com/boucher/1750375). I am using PHP and Stripe.js and I keep getting this error:
The 'exp_month' parameter should be an integer (instead, is undefined)
Below is the code I am using. Am I missing something obvious?
<?php
session_start();
$name = htmlspecialchars($_POST['name']);
$description = "Test Transaction";
$amount = trim($_POST['amount']);
$email = htmlspecialchars(trim($_POST['email']));
$receipt_error = "Email receipt did not send!";
require_once 'includes/stripe-php-1.12.0/lib/Stripe.php';
if ($_POST) {
Stripe::setApiKey("sk_test_XXXXXX");
$error = '';
$success = '';
try {
if (!isset($_POST['stripeToken']))
throw new Exception("The Stripe Token was not generated correctly");
Stripe_Charge::create(array("amount" => $amount * 100,
"description" => $description,
"currency" => "usd",
"card" => $_POST['stripeToken']));
//PREPARE EMAIL
$to = $email;
$subject = "Receipt";
$headers =
'From: XXXX ' . "\r\n" .
'Reply-To: XXXX ' . "\r\n" .
'Bcc: XXXX' . "\r\n" .
'Content-type: text/html' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
include_once('includes/email_receipt.php'); //Sent $message
//Send the email!
if(mail($to,$subject,$message,$headers)){
header("Location: thank-you.php");
}
else{
die($receipt_error);
}
}
catch (Exception $e) {
$error = $e->getMessage();
}
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<!-- jQuery is used only for this example; it isn't required to use Stripe -->
<script type="text/javascript">
// this identifies your website in the createToken call below
Stripe.setPublishableKey('pk_test_XXX');
function stripeResponseHandler(status, response) {
if (response.error) {
// re-enable the submit button
$('.submit_button').removeAttr("disabled");
// show the errors on the form
$(".payment-errors").html(response.error.message);
} else {
var form$ = $("#donation_form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// and submit
form$.get(0).submit();
}
}
$(document).ready(function() {
$("#donation_form").submit(function(event) {
// disable the submit button to prevent repeated clicks
$('.submit_button').attr("disabled", "disabled");
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.createToken({
number: $('.number').val(),
name: $('.name').val(),
description: $('.description').val(),
cvc: $('.cvc').val(),
exp_month: $('.exp_month').val(),
exp_year: $('.exp_year').val()
}, stripeResponseHandler);
return false; // submit from callback
});
});
</script>
<form method="post" action="" class="reply-input" id="donation_form" >
<div class="input-block">
<label for="amount" class="label_comment"><strong>Donation Amount</strong>*</label>
<input type="text" name="amount" value="<?php echo $_POST['amount']; ?>" placeholder="$" data-stripe="amount" id="amount" required="">
</div>
<div class="input-block">
<label for="name" class="label_comment"><strong>Cardholder Name</strong>*</label>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" data-stripe="name" id="name" required="">
</div>
<div class="input-block">
<label for="email" class="label_comment"><strong>Email</strong>*</label>
<input type="email" name="email" value="<?php echo $_POST['email']; ?>" data-stripe="email" id="email" required="">
</div>
<div class="input-block">
<label for="credit_card" class="label_comment"><strong>Credit Card Number</strong>*</label>
<input type="number" name="credit-card" value="" id="credit_card" data-stripe="number" required="">
</div>
<div class="input-block">
<label for="cvc" class="label_comment"><strong>CVV</strong>*</label>
<input type="number" name="cvc" value="" data-stripe="cvc" id="cvv" required="" maxlength="4">
</div>
<div class="input-block">
<label for="exp_month" class="label_comment"><strong>Expiration Month</strong>*</label>
<div class="clear"></div>
<select name='exp_month' id='exp_month' data-stripe="exp-month">
<option value=''>Month</option>
<option value='01'>Janaury</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='04'>April</option>
<option value='05'>May</option>
<option value='06'>June</option>
<option value='07'>July</option>
<option value='08'>August</option>
<option value='09'>September</option>
<option value='10'>October</option>
<option value='11'>November</option>
<option value='12'>December</option>
</select>
<select name='exp_year' id='exp_year' data-stripe="exp-year">
<option value="">Year</option>
<?php
for($i=0;$i<21;$i++){
echo "<option value='".(date('Y')+$i)."'>".(date('y')+$i)."</option>\n";
}
?>
</select>
</div>
<input type="submit" class="btn btn-success btn-large submit_button" value="Click to Donate Today">
<div class="clear"></div>
</form>
In your code, you're querying by classname '.exp_month' when there isn't a class with '.exp_month' in your HTML. If you're trying to query by id, it should be $('#exp_month')
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")
The code of the contact form below gives me an error FORM SENDING FAILED.
Can you please help me resolve the issue?The code of the contact form below gives me an error FORM SENDING FAILED.
Can you please help me resolve the issue?The code of the contact form below gives me an error FORM SENDING FAILED.
Can you please help me resolve the issue?
<form id="contactform" method="post" action="$_SELF">
<label class="hide" for="author">Full Name</label>
<input class="input-fields" id="author" name="name" type="text" placeholder="Full Name" value="" required autofocus />
<label class="hide" for="email">Email</label>
<input class="input-fields" id="email" name="email" type="text" placeholder="Email Address" value="" autofocus />
<label class="hide" for="email">Mobile No</label>
<input class="input-fields" id="email" name="phone_no" type="text" placeholder="Mobile No" value="" autofocus />
<label class="hide" for="author">Company</label>
<input class="input-fields" id="author" name="company" type="text" placeholder="Company" value="" required autofocus />
<label class="hide" for="select_category">Select a Industry:</label>
<span id="select_group" class="select-group">
<select name="vehicle">
<option value="General" >Select a Industry:</option>
<option value="General" >Health Centres Hospitals</option>
<option value="Sales" >Tradeshows Conferences</option>
<option value="Support" >Fast Foods and Restaurants</option>
<option value="Support" >Night CLub, Bars and Disos</option>
<option value="Support" >Banks , Rent Estate</option>
<option value="Support" >Educational Institute</option>
<option value="Support" >Recreational Facilities</option>
<option value="Support" >Malls,Luxury Retail and Store Windows</option>
</select>
</span>
<label class="hide" for="subject_title">Solutions</label>
<input class="input-fields" id="subject_title" name="solution" type="text" placeholder="Solutions" value="" autofocus />
<label class="hide" for="author">Require</label>
<input class="input-fields" id="author" name="require" type="text" placeholder="Require" value="" required autofocus />
<label class="hide" for="comment">Message</label>
<textarea id="comment" class="input-fields" placeholder="Message" name="message" cols="40" rows="200"></textarea>
<span class="form_response">
<ul id="errors" class="">
<li id="info">There were some problems with your form submission:</li>
</ul>
<p id="success" class="">Thanks for your message! We will get back to you ASAP!</p>
</span>
<input name="submit" type="submit" id="submit-contact-info" class="contact-info-submit form-submit-button span2" value="Send message">
</form>
</div>
</div>
</article>
</main>
</div>
<?php
//If the form is submitted
echo "hello";
if(isset($_REQUEST['submit']))
{
$message = $_POST['message'];
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['vehicle']) == '') {
$hasError = true;
} else {
$vehicle = trim($_POST['vehicle']);
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['require']) == '') {
$hasError = true;
} else {
$require = trim($_POST['require']);
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['solution']) == '') {
$hasError = true;
} else {
$solution = trim($_POST['solution']);
}
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure that the mobile no field is not empty
if(trim($_POST['phone_no']) == '') {
$hasError = true;
} else {
$phone_no = trim($_POST['phone_no']);
}
//If there is no error, send the email
if(!isset($hasError))
{
$emailTo = "sahil7771#gmail.com"; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nMobile No: $phone_no \n\n Your Industry: $vehicle \n\
\n\n Your Requirement: $require \n\n Your Solution: $solution \n\n
\n\n Message : $message
\n\nPlease Contact $name on $phone_no\n \n /====================================/ ";
$headers = 'From: Touch Active <'. $emailTo .'>' . "\r\n" . 'Reply-To: ' . $email;
if(mail($emailTo, 'Mail From Touch Active', $body, $headers))
{ //Replace Your Website Subject
$response=1;
$emailSent = true;
?>
<div id="responsive-container" ><p>Thanks For Messaging Us You Will Shortly Expect Our Assistance ( With In 24hrs ).</p></div>
<?php
}
else
{
?>
<div id="page-title"><h2>Failed To Sent</h2></div>
<?php
$response=0;
}
}
?>
Change in form action="$_SELF" to action="$_SERVER['PHP_SELF']", because there isn't constant like $_SELF.
Actually its working here with no errors
try it with this little script, to check or e-mail is permitted :
<?php
$to = "somebody#example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster#example.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$txt,$headers);
?>
I have tested your script with minor adjustment:
<form id="contactform" method="post" action="#">
<label class="hide" for="author">Full Name</label>
<input class="input-fields" id="author" name="name" type="text" placeholder="Full Name" value="aaa" required autofocus />
<label class="hide" for="email">Email</label>
<input class="input-fields" id="email" name="email" type="text" placeholder="Email Address" value="xxx#boboba.com" autofocus />
<label class="hide" for="email">Mobile No</label>
<input class="input-fields" id="email" name="phone_no" type="text" placeholder="Mobile No" value="0322233355" autofocus />
<label class="hide" for="author">Company</label>
<input class="input-fields" id="author" name="company" type="text" placeholder="Company" value="aaa" required autofocus />
<label class="hide" for="select_category">Select a Industry:</label>
<span id="select_group" class="select-group">
<select name="vehicle">
<option value="General" >Select a Industry:</option>
<option value="General" >Health Centres Hospitals</option>
<option value="Sales" >Tradeshows Conferences</option>
<option value="Support" >Fast Foods and Restaurants</option>
<option value="Support" >Night CLub, Bars and Disos</option>
<option value="Support" >Banks , Rent Estate</option>
<option value="Support" >Educational Institute</option>
<option value="Support" >Recreational Facilities</option>
<option value="Support" >Malls,Luxury Retail and Store Windows</option>
</select>
</span>
<label class="hide" for="subject_title">Solutions</label>
<input class="input-fields" id="subject_title" name="solution" type="text" placeholder="Solutions" value="aaa" autofocus />
<label class="hide" for="author">Require</label>
<input class="input-fields" id="author" name="require" type="text" placeholder="Require" value="aaa" required autofocus />
<label class="hide" for="comment">Message</label>
<textarea id="comment" class="input-fields" placeholder="Message" name="message" cols="40" rows="20"></textarea>
<span class="form_response">
<ul id="errors" class="">
<li id="info">There were some problems with your form submission:</li>
</ul>
<p id="success" class="">Thanks for your message! We will get back to you ASAP!</p>
</span>
<input name="submit" type="submit" id="submit-contact-info" class="contact-info-submit form-submit-button span2" value="Send message">
</form>
</div>
</div>
</article>
</main>
</div>
<?php
//If the form is submitted
if(isset($_REQUEST['submit']))
{
$message = $_POST['message'];
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['vehicle']) == '') {
$hasError = "1";
} else {
$vehicle = trim($_POST['vehicle']);
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['require']) == '') {
$hasError = "2";
} else {
$require = trim($_POST['require']);
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['solution']) == '') {
$hasError = "3";
} else {
$solution = trim($_POST['solution']);
}
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = "4";
} else {
$name = trim($_POST['name']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = "5";
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = "6";
} else {
$email = trim($_POST['email']);
}
//Check to make sure that the mobile no field is not empty
if(trim($_POST['phone_no']) == '') {
$hasError = "7";
} else {
$phone_no = trim($_POST['phone_no']);
}
//If there is no error, send the email
if(!isset($hasError))
{
echo "OK";
$emailTo = "sahil7771#gmail.com"; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nMobile No: $phone_no \n\n Your Industry: $vehicle \n\
\n\n Your Requirement: $require \n\n Your Solution: $solution \n\n
\n\n Message : $message
\n\nPlease Contact $name on $phone_no\n \n /====================================/ ";
$headers = 'From: Touch Active <'. $emailTo .'>' . "\r\n" . 'Reply-To: ' . $email;
if(mail($emailTo, 'Mail From Touch Active', $body, $headers))
{ //Replace Your Website Subject
$response=1;
$emailSent = true;
?>
<div id="responsive-container" ><p>Thanks For Messaging Us You Will Shortly Expect Our Assistance ( With In 24hrs ).</p></div>
<?php
}
else
{
?>
<div id="page-title"><h2>Failed To Sent</h2></div>
<?php echo "NOK";
echo $hasError;
echo $response;
$response=0;
}
}
else{
echo $hasError;
}
?>