Succeeding submission of contact form - php

Hi I have a contact form using PHP AJAX but filling the form, it is successful but when I try to fillup again the form it is not submitting unless I refresh the page, it will go back to normal again. What will be the problem of this?
Thanks
HTML Code
<form role="form" id="feedbackForm" method="POST">
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="textinput">First Name<span class="required">*</span></label>
<input type="text" class="form-control required" id="first_name" name="first_name" placeholder="Enter your First Name"/>
<span class="help-block" style="display: none;">Please enter your first name.</span>
</div>
<div class="form-group">
<label class="control-label" for="textinput">Last Name<span class="required">*</span></label>
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Enter your Last Name"/>
<span class="help-block" style="display: none;">Please enter your last name.</span>
</div>
<div class="form-group">
<label class="control-label" for="textinput">Email Address<span class="required">*</span></label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email address"/>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div id="companyname_con" class="form-group">
<label class="control-label" for="textinput">Company Name</label>
<input type="text" class="form-control" id="company_name" name="company_name" placeholder="Enter your company name">
</div>
<div class="form-group">
<label class="control-label" for="textinput">Message<span class="required">*</span></label>
<textarea rows="10" cols="100" class="form-control" id="contact_message" name="contact_message" placeholder="Enter your message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="selectbasic">How did you hear about us?</label>
<select id="selectbasic" name="selectbasic" class="form-control">
<option value="None">Select</option>
<option value="Search Engine">Search engine</option>
<option value="Microsoft DPE">Microsoft DPE</option>
<option value="Microsoft Event">Microsoft event</option>
<option value="Social Media">Social media</option>
<option value="Word of Mouth">Word of mouth</option>
<option value="Other">Other</option>
</select>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="emailUpdates" name="emailUpdates" value="Yes"> Please keep me informed of kinectAPI product updates and news
</label>
</div>
<img id="captcha" src="library/vender/securimage/securimage_show.php" alt="CAPTCHA Image" />
Show a Different Image<br/>
<div class="form-group" style="margin-top: 10px;">
<input type="text" class="form-control" name="captcha_code" id="captcha_code" placeholder="For security, please enter the code displayed in the box." />
<span class="help-block" style="display: none;">Please enter the code displayed within the image.</span>
</div>
<span class="help-block" style="display: none;">Please enter a the security code.</span>
<button type="submit" id="feedbackSubmit" class="btn btn-purple btn-md message-btn">Submit Message</button>
</div>
</form>
PHP Code
<?php
//start a session -- needed for Securimage Captcha check
session_start();
//add you e-mail address here
define("MY_EMAIL", "dummy#email.com");
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($contact_message) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $contact_message)));
}
/**
* Return a formatted message body of the form:
* Name: <name of submitter>
* Comment: <message/comment submitted by user>
*
* #param String $name name of submitter
* #param String $messsage message/comment submitted
*/
function setMessageBody ($first_name, $last_name, $email, $company_name,
$contact_message, $selectbasic) {
$message_body .= "First Name: " . $first_name."\n\n";
$message_body .= "Last Name: " . $last_name."\n\n";
$message_body .= "Email: " . $email."\n\n";
$message_body .= "Company Name:" . $company_name."\n\n";
$message_body .= "Message:" . $contact_message. "\n\n";
$message_body .= "How did you hear about us?" . $selectbasic."\n\n";
return $message_body;
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$company_name = $_POST['company_name'];
$contact_message = $_POST['contact_message'];
$selectbasic = $_POST['selectbasic'];
header('Content-type: application/json');
//do some simple validation. this should have been validated on the client-side also
if (empty($email) || empty($contact_message)) {
errorResponse('Email or message is empty.');
}
//do Captcha check, make sure the submitter is not a robot:)...
include_once './vender/securimage/securimage.php';
$securimage = new Securimage();
if (!$securimage->check($_POST['captcha_code'])) {
errorResponse('Invalid Security Code');
}
//try to send the message
if(mail(MY_EMAIL, "Contact Form Results", setMessageBody($_POST["first_name"],
$_POST["last_name"], $_POST["email"], $_POST["company_name"], $_POST["contact_message"],
$_POST["selectbasic"]), "From: $email")) {
echo json_encode(array('message' => 'Your message was successfully sent'));
} else {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(array('message' => 'Unexpected error while attempting to send e-
mail.'));
}
?>
JS code
$(document).ready(function() {
$("#feedbackSubmit").click(function() {
//clear any errors
contactForm.clearErrors();
//do a little client-side validation -- check that each field has a value and e-mail field is in proper format
var hasErrors = false;
$('#feedbackForm input,textarea').each(function() {
if (!$(this).val()) {
hasErrors = true;
contactForm.addError($(this));
}
});
var $email = $('#email');
if (!contactForm.isValidEmail($email.val())) {
hasErrors = true;
contactForm.addError($email);
}
//if there are any errors return without sending e-mail
if (hasErrors) {
return false;
}
//mailchimp trigger
if($('#emailUpdates').prop('checked')) {
$.ajax({
type: "POST",
url: 'subscribe.php',
data: 'ajax=true&email=' + escape($('#email').val())
});
}
//send the feedback e-mail
$.ajax({
type: "POST",
url: "library/sendmail.php",
data: $("#feedbackForm").serialize(),
success: function(data)
{
contactForm.addAjaxMessage(data.message, false);
//get new Captcha on success
$('#captcha').attr('src', 'library/vender/securimage/securimage_show.php?' +
Math.random());
},
error: function(response)
{
contactForm.addAjaxMessage(response.responseJSON.message, true);
}
});
$('#feedbackForm input,textarea,select').val('');
return false;
});
});
//namespace as not to pollute global namespace
var contactForm = {
isValidEmail: function (email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
},
clearErrors: function () {
$('#emailAlert').remove();
$('#feedbackForm .help-block').hide();
$('#feedbackForm .form-group').removeClass('has-error');
},
addError: function ($input) {
$input.siblings('.help-block').show();
$input.parent('.form-group').addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ?
'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() +
'</div>');
}
};

Related

Ajax form validation in php

Im trying to create ajax from with php validation, let explain with screenshot. while validating form im getting all error in same placeā€¦
what im trying to get is individual validation for field like below
And after form is submitted i want display success message at the top of form but im getting success message on all field
html form data (index.php)
<form id="first_form" method="POST" action="form.php">
<p class="form-message"></p>
<div class="mb-3">
<input type="text" class="form-control" id="name" name="name" placeholder="Name:">
<p class="form-message"></p>
</div>
<div class="mb-3">
<input type="tex" class="form-control" id="email" name="email" placeholder="Email:">
<p class="form-message"></p>
</div>
<div class="mb-3">
<input type="text" class="form-control" id="phone" name="phone" placeholder="Phone:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="address" name="address" placeholder="Address:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="services" name="services" placeholder="Services:">
</div>
<div class="mb-3">
<textarea class="form-control" rows="5" id="message" name="message" placeholder="Leave Your Message..."></textarea>
</div>
<button type="submit" name="submit" id="submit" class="btn btn-primary">Submit</button>
js code:
$(document).ready(function() {
$("#first_form").submit(function(event) {
event.preventDefault();
name = $("#name").val();
email = $("#email").val();
phone = $("#phone").val();
address = $("#address").val();
subject = $("#subject").val();
services = $("#services").val();
message = $("#message").val();
submit = $("#submit").val();
$(".form-message").load("form.php", {
name: name,
email: email,
phone: phone,
address: address,
subject: subject,
services: services,
message: message,
submit: 'submitted'
});
});
});
form.php data
if (isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = "Contact Form";
$mailTo = "hello#develoweb.com";
$headers = "From: ".$email;
$txt = "You have received a message from ".$name.
".\n\n".$message;
$errorEmptyname = false;
$errorEmptyemail = false;
$errorEmptymessage = false;
$errorEmail = false;
if (empty($name)) {
echo "<span class='form-error'>Name Field cannot be empty</span> ";
//$errorEmptyName = true;
}
if (empty($email)) {
echo "<span class='form-error'>Email Field cannot be empty</span>";
//$errorEmptyemail = true;
}
if (empty($message)) {
//$errorEmptymessage = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>
Write a valid e-mail addres </span>";
$errorEmail = true;
}
else {
echo "<span class='form-success'>
Thank you for your message!<br>
I'll get back to you as soon as I can.</span>";
mail($mailTo, $subject, $body, $headers);
}
}
else{
echo "There was an error!";
}
what i have understand, im not getting individual validation error in individual field bcz class is same, how can i append error to related fields
i havent used js validation bcz i want to some validation for spammer to prevent spam mail and as we know while viewing source code we can easily view code for validation too, so pefer validation in php

I am unable to send values of multiple checkboxes to php email script

I have form which contains multiple checkboxes and i need to send their values to the email but i am unable to send it through the ajax to email script.
But without ajax php code is working please suggest where i am missing something
Below is my html code
<form enctype="multipart/form-data">
<div class="col-md-12 col-sm-12"><input type="text" id="name" name="name" placeholder="Name:*" class="form-control" required/></div>
<div class="col-md-12 col-sm-12"><input type="email" id="email" name="email" placeholder="Email:*" class="form-control" required/></div>
<div class="col-md-12 col-sm-12"><input type="text" id="phone" name="phone" placeholder="Phone:*" class="form-control" required/></div>
<p>Vehicle Type You're Shipping?:*</p>
<div class="input-holder field-checkbox">
<div class="field-element ">
<input type="checkbox" id="" name="checkbox[]" value="Car, Truck Or SUV" class="required ">
<label for="1dfb36b53196072fe797a082d9892947-3-0">Car, Truck Or SUV</label>
</div>
<div class="field-element ">
<input type="checkbox" id="" name="checkbox[]" value="Motorcycle Or ATV" class="required ">
<label for="1dfb36b53196072fe797a082d9892947-3-1">Motorcycle Or ATV</label>
</div>
<div class="field-element ">
<input type="checkbox" id="" name="checkbox[]" value="RV Or Motorhome" class="required ">
<label for="1dfb36b53196072fe797a082d9892947-3-2">RV Or Motorhome</label>
</div>
<div class="field-element ">
<input type="checkbox" id="" name="checkbox[]" value="Boat/Yacht, Jet Ski" class="required ">
<label for="1dfb36b53196072fe797a082d9892947-3-3">Boat/Yacht, Jet Ski</label>
</div>
<div class="field-element ">
<input type="checkbox" id="" name="checkbox[]" value="Trailer" class="required ">
<label for="1dfb36b53196072fe797a082d9892947-3-4">Trailer</label>
</div>
<div class="field-element ">
<input type="checkbox" id="" name="checkbox[]" value="Other" class="required ">
<label for="1dfb36b53196072fe797a082d9892947-3-5">Other</label>
</div>
SEND
<center> <div class="result" id="result"style="color:red;font-weight: 900;background: #fff; "></div></center>
</form>
and i have this code for ajax
<script>
function submit_user(){
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
var country = document.getElementById('country').value;
var current = document.getElementById('current').value;
var model = document.getElementById('model').value;
var enquiry = document.getElementById('enquiry').value;
var myCheckboxes = new Array();
$("input:checkebox").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
$.ajax({
type: "POST",
url: "script.php?name="+name+"&email="+email+"&phone="+phone+"&checkbox="+myCheckboxes+"&country="+country+"&current="+current+"&model="+model+"&enquiry="+enquiry,
success:function(data) {
$( ".result" ).html(data);
}
});
// alert("2s");
}
and i have this script for php
<?php
if (!empty($_GET['name']) && !empty($_GET['email']) && !empty($_GET['phone'] ) && !empty($_GET['country']) && !empty($_GET['current']) && !empty($_GET['model'])) {
$message = "New Email from landing Page";
$name = $_GET['name'];
$email = $_GET['email'];
$phone = $_GET['phone'];
$country =$_GET['country'];
$current =$_GET['current'];
$model =$_GET['model'];
$enquiry =$_GET['enquiry'];
$from = "From: Booking from Landing Page";
$to = "email#gmail.com";
$subject = " You Got a Booking From Landing Page!";
if (isset($_GET['myCheckboxes']) && !empty($_GET['myCheckboxes'])) {
foreach($_GET['myCheckboxes'] as $selected ){
$MESSAGE_BODY .= $selected."\r\n";
}
}
$mail = "
Info: ".$message."
Name: ".$name."
email: ".$email."
Phone: ".$phone."
checkbox ".$MESSAGE_BODY."
Country: ".$country."
Currrent: ".$current."
Model: ".$model."
Message: ".$enquiry."";
mail($to, $subject, $mail, $from);
//readfile("thank-you.html");
//exit;
echo "Thank You, I will get back to you ASAP";
}else{
//readfile("error.html");}
echo "something is incorrect, please retry";
}
?>
Try changing -
var myCheckboxes = new Array();
$("input:checkebox").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
to
var myCheckboxes = new Array();
$("input:checkbox:checked").each(function() {
myCheckboxes.push($(this).val());
});
(1) input:checkebox should be input:checkbox
(2) added :checked as you only want to send checked checkboxes, not each one
(3) you want to .push() to myCheckboxes, not to data['myCheckboxes[]']

Jquery- Putting an attachment in form and send to email

I'm having a problem on how to add an attachment in my working form, i'm using Bootstrap, JQuery and PHP. i have no idea on how to add an attachment where the user will attach their Resume's and then send it to email.
i hope you can help me with this without changing my entire code. is it even possible?.
This is my initial input form
<section class = "resume section-padding" id = "resume "><div class="form-group col-md-6">
<label for="fName">First Name</label>
<input type="text" class="form-control" id="fName" placeholder="First Name">
</div>
<div class="form-group col-md-6">
<label for="lName">Last Name</label>
<input type="text" class="form-control" id="lName" placeholder="Last Name">
</div>
<div class = "form-group col-md-12">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="Address">
</div>
<div class = "form-group col-md-4">
<label for="doBirth">Date of Birth</label>
<input type="date" class="form-control" id="doBirth" placeholder="Date of Birth">
</div>
<div class = "form-group col-md-4">
<label for="city">City</label>
<input type="text" class="form-control" id="city" placeholder="City">
</div>
<div class = "form-group col-md-4">
<label for="zipCode">ZIP CODE</label>
<input type="number" class="form-control" id="zipCode" placeholder="ZIP">
</div>
<div class = "form-group col-md-6">
<label for="email">E-mail</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class = "form-group col-md-6">
<label for="phone">Phone</label>
<input type="number" class="form-control" id="phone" placeholder="Phone Number">
</div>
</div>
This is my jquery it will get the value of the form.
$('.resume #getResume').on('click', function(e){
e.preventDefault();
var fName = $('#fName').val();
var lName = $('#lName').val();
var address = $('#address').val();
var doBirth = $('#doBirth').val();
var city = $('#city').val();
var zipCode = $('#zipCode').val();
var email = $('#email').val();
var phone = $('#phone').val();
var form = new Array({ 'fName':fName, 'lName':lName, 'address':address, 'doBirth':doBirth, 'city':city, 'zipCode':zipCode,
'email':email, 'phone':phone });
$.ajax({
type: 'POST',
url: "/path/to/url.php",
data: ({'action': 'resume', 'form': form})
}).done(function(data) {
$('#resume .result').html(data);
$(".resume")[0].reset();
});
});
This is my php this where my jQuery will pass the value
$sendTo = "email#email.com";
$action = $_POST['action'];
$name = $_POST['form'][0]['name'];
$email = $_POST['form'][0]['email'];
$subject = $_POST['form'][0]['subject'];
$message = $_POST['form'][0]['message'];
if ($name == "" || $email == "" || $message == "" || $subject == "") {
echo "<p class=\"error\">There was problem while sending E-Mail. Please verify entered data and try again!</p>";
exit();
}
else
{
$header = 'From: ' . $name . '<' . $email . ">\r\n" .
'Reply-To: ' . $email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sent = mail($sendTo, $subject, $message, $header);
if ($sent) {
echo "<p class=\"success\">Message sent succesfully.</p>";
} else {
echo "<p class=\"error\">There was problem while sending E-Mail.</p>";
}
}
?>
If you are not using any framework and in core php it is very easy to upload a file. You can see all the code and working here for better understanding. This is good source to get thing done.
In your current code just add a field to upload a file. Like this
<input type="file" name="fileToUpload" id="fileToUpload">
. Also dont forget to ON the file_uploads in php.ini file.
To add it in the email:
for adding in the email just catch the file in the script file and send it to the email like this.
$email->AddAttachment( $file_to_attach , 'NameOfFile.pdf' );

Validate name in contact form using php - $error incorrect?

I'm having trouble validating the name in my contact form. If the name field is left empty, the form should generate an error message such as "Please enter your name". Instead there is no error message and the e-mail is allowed to be sent. Here's my code:
<form id="ajax-contact-form" class="form-horizontal" action="javascript:alert('success!');">
<div class="row">
<div class="span4">
<div class="control-group">
<label class="control-label" for="inputName">Your full name:</label>
<div class="controls">
<input class="span4" type="text" id="inputName" name="name" value="Your full name:" onBlur="if(this.value=='') this.value='Your full name:'" onFocus="if(this.value =='Your full name:' ) this.value=''">
</div>
</div>
</div>
<div class="span4">
<div class="control-group">
<label class="control-label" for="inputEmail">Your email:</label>
<div class="controls">
<input class="span4" type="text" id="inputEmail" name="email" value="Your email:" onBlur="if(this.value=='') this.value='Your email:'" onFocus="if(this.value =='Your email:' ) this.value=''">
</div>
</div>
</div>
<div class="span4">
<div class="control-group">
<label class="control-label" for="inputPhone">Phone number:</label>
<div class="controls">
<input class="span4" type="text" id="inputPhone" name="phone" value="Phone number:" onBlur="if(this.value=='') this.value='Phone number:'" onFocus="if(this.value =='Phone number:' ) this.value=''">
</div>
</div>
</div>
<div class="span4">
<div class="control-group">
<label class="control-label" for="inputDrums">Do you have a drum set?</label>
<div class="controls">
<select input class="" type="text" id="inputDrums" name="drums">
<option>Do you have a drum set?</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
</div>
</div>
<div class="span4">
<div class="control-group">
<label class="control-label" for="inputLevel">What level is the student?</label>
<div class="controls">
<select input class="span4" type="text" id="inputLevel" name="level">
<option>What level is the student?</option>
<option>Beginner</option>
<option>Intermediate</option>
<option>Advanced</option>
</select>
</div>
</div>
</div>
<div class="span4">
<div class="control-group">
<label class="control-label" for="inputCity">What city do you live in?</label>
<div class="controls">
<select input class="span4" type="text" id="inputCity" name="city">
<option>What city do you live in?</option>
<option>Boulder</option>
<option>Erie</option>
<option>Gunbarrel</option>
<option>Lafayette</option>
<option>Longmont</option>
<option>Louisville</option>
<option>Niwot</option>
<option>Other</option>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="span12">
<div class="control-group">
<label class="control-label" for="inputMessage">Message:</label>
<div class="controls">
<textarea class="span12" id="inputMessage" name="content" onBlur="if(this.value=='') this.value='Message:'"
onFocus="if(this.value =='Message:' ) this.value=''">Message:</textarea>
</div>
</div>
</div>
</div>
<div class="row">
<div class="span12">
<div class="control-group captcha">
<label class="control-label" for="inputCaptcha">Enter captcha numbers here:</label>
<div class="controls">
<input class="" type="text" id="inputCaptcha" name="captcha" value="Enter captcha numbers here:" onBlur="if(this.value=='') this.value='Enter captcha numbers here:'" onFocus="if(this.value =='Enter captcha numbers here:' ) this.value=''">
<img src="captcha/captcha.php">
<img src="images/trans.png" style="width: 5px; height: 5px">
<INPUT TYPE="button" onClick="history.go(0)" VALUE="Refresh captcha" style="width: 120px; height: 42px">
</div>
</div>
</div>
</div>
<button type="submit" class="submit">Send</button>
</form>
**Contact.php**
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
include 'contact_config.php';
session_start();
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$phone = stripslashes($_POST['phone']);
$drums = stripslashes($_POST['drums']);
$level = stripslashes($_POST['level']);
$city = stripslashes($_POST['city']);
$subject = "Website Inquiry";
$message = "
Name: ".$_POST['name']
."
E-mail Address: ".$_POST['email']
."
Phone: ".$_POST['phone']
."
Drums: ".$_POST['drums']
."
Level: ".$_POST['level']
."
City: ".$_POST['city']
."
Message: ".$_POST['content'];
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
if(isset($_SESSION['captcha_keystring']) && strtolower($_SESSION['captcha_keystring']) != strtolower($_POST['captcha']))
{
$error .= "Incorrect captcha.<br />";
}
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>';
}
}
?>
**functions.php**
<?php
function ValidateEmail($email)
{
$regex = '/([a-z0-9_.-]+)'. # name
'#'. # at
'([a-z0-9.-]+){2,255}'. # domain & possibly subdomains
'.'. # period
'([a-z]+){2,10}/i'; # domain extension
if($email == '') {
return false;
}
else {
$eregi = preg_replace($regex, '', $email);
}
return empty($eregi) ? true : false;
}
?>
Your $_POST['name'] may not be actually empty it could be something like ' '. Replace
if(!$name){//...
with
if(empty($name)){//...
You could also trim your strings as well. e.g.
$name = trim(stripslashes($_POST['name']));
Use isset to verify if the parameter was sent or not
if(!isset($_POST['name']))
{
$error .= 'Please enter your name.<br />';
}
Try printing the $error parameter before the condition and see what the output is.
About the email varification you can use the PHP build in filters:
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_b) email address is considered valid.";
}
Example #1 Validating email addresses with filter_var()
In my testing, I have found that empty strings always evaluate to false, so if the $_POST['name'] variable is an empty string, your code should work.
It may be, then, that you are receiving white space (e.g. a space or newline) from your form without realising it. In this case, you can filter your $_POST variable like so:
$filtered = array_map("stripslashes", array_filter(array_map("trim", $_POST)));
Having done this, $filtered['name'] will not be set if $_POST['name'] is empty or only whitespace. This can be checked with either isset or array_key_exists.
Change the value to placeholder
Original code
<input class="span4" id="inputName" name="name" value="Your full name:" onblur="if(this.value=='') this.value='Your full name:'" onfocus="if(this.value =='Your full name:' ) this.value=''" type="text">
To
changed code
<input class="span4" id="inputName" name="name" placeholder="your full name" type="text">
A place holder will appear in the input field. But When you add something to the field, the placeholder will disappear. Also when your clear text in the input field (make the input field empty) and you focus out of it, the input field will retain its placeholder value.
do this for all the input fields such as email.
But If you still want to keep the onfocus and onblur events, call this function on submit (Although I dont recommmend as this as it will only work if javascript on the client side is enabled).
function()
{
var name = document.getElementById('inputName');
if(name.value === "Your full name:" || name.value === "")
{
return false;
}
}

PHP file upload with Ajax

I am working on a form where we need to upload the file. The form is processing with Ajax and the data is being posted on the email with no problem except file upload.
Now we want to allow user to upload multiple image files that will be stored on our server and we will get the link to the images in the email.
Please have a look at the codes below:
Form HTML code:
<div class="col-sm-12">
<div class="well">
<form id="ajax-contact" action="http://websitename.com/mailer.php" method="post" enctype="multipart/form-data">
<h2>Personal Details</h2>
<div class="login-wrap">
<div class="form-group">
<label class="control-label" for="name">Name</label>
<input name="name" placeholder="enter your name" id="name" class="form-control" type="text">
</div>
<div class="form-group">
<label class="control-label" for="tel">Telephone</label>
<input name="tel" placeholder="enter your telephone" id="tel" class="form-control" type="text">
</div>
<div class="form-group">
<label class="control-label" for="email">Email</label>
<input name="email" placeholder="enter your email" id="input-email" class="form-control" type="text">
</div>
<div class="form-group">
<label class="control-label" for="comments">Comments</label>
<textarea name="comments" placeholder="your comments" id="comments" class="form-control" type="text"></textarea>
</div>
</div>
<h2 style="margin-top:20px;">Product Details</h2>
<div class="login-wrap">
<div class="form-group">
<label class="control-label" for="make">Make/Brand</label>
<input name="make" placeholder="enter your make" id="make" class="form-control" required="" type="text">
</div>
<div class="form-group">
<label class="control-label" for="model">Model</label>
<input name="model" placeholder="enter your model" id="model" class="form-control" required="" type="text">
</div>
<div class="form-group">
<label class="control-label" for="reference">Reference Number</label>
<input name="reference" placeholder="enter your reference" id="reference" class="form-control" type="text">
</div>
<div class="form-group">
<label class="control-label" for="condition">Condition</label>
<select id="condition" name="condition" required="">
<option>Mint</option>
<option>Used</option>
</select>
</div>
<div class="form-group">
<label for="images">Upload Images</label>
<input id="images" name="images" multiple="" required="" type="file">
<p class="help-block">upload maximum 4 images</p>
</div>
<div class="form-group">
<label class="control-label" for="price">Expected Price</label>
<input name="price" placeholder="enter your price" id="price" class="form-control" required="" type="text">
</div>
<div class="checkbox">
<label>
<input value="" type="checkbox">
With Box
</label>
</div>
<div class="checkbox disabled">
<label>
<input value="" type="checkbox">
With Papers
</label>
</div>
</div>
<input value="Submit" class="btn btn-primary button" type="submit">
</form>
</div>
</div>
</div>
AJAX:
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
$('#tel').val('');
$('#make').val('');
$('#model').val('');
$('#reference').val('');
$('#condition').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
PHP Form Processor:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$tel = filter_var(trim($_POST["tel"]));
$message = trim($_POST["message"]);
$make = trim($_POST["make"]);
$model = trim($_POST["model"]);
$reference = trim($_POST["reference"]);
$condition = trim($_POST["condition"]);
// Check that data was sent to the mailer.
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "myemail#mycompany.com";
// Set the email subject.
$subject = "New Contact form Submitted";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Tel: $tel\n";
$email_content .= "Email: $email\n";
$email_content .= "Message: $message\n";
$email_content .= "Make/Brand: $make\n";
$email_content .= "Model: $model\n";
$email_content .= "Reference: $reference\n";
$email_content .= "Condition: $condition\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

Categories