One Page Contact Form PHP & Script - php

I am making a one page website, and I would like to add a contact form in one section. So I am working with PHP, thing is, I cant seem to find any base pre-made forms that do not open a new webpage or direct that you to a new page once you submit. I would like to keep this one page, so I would like an overlay to appear once everything is all correct in the form and it has been submitted. No popups or redirects. This may require jQuery but I am not sure how to put it in so it actually does that.
Here is how I have set up the form in HTML:
<form action="mail.php" method="post" enctype="multipart/form-data" >
<label></label>
<input name="name" required placeholder="Your Name">
<label></label>
<input name="email" type="email" required placeholder="Your Email">
<label></label>
<textarea name="message" cols="20" rows="5" required placeholder="Message"></textarea>
<input id="submit" name="submit" type="submit" value="Submit">
</form>
Here is mail.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: Website';
$to = 'email#emailhere.com';
$subject = 'Email Inquiry';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";?>
<?php
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Thank you for your message! </p>';
} else {
echo '<p>An error occurred. Try sending your message again.</p>'; }}?>
Now, I would like to be able to remove the echo for the thank you message, and replace it with jQuery code for an overlay I made.
$(document).ready(function() {
$("#overlay").show();
});
I am missing a part of the function, as right now its just going to show when the page is ready. But I don't know where to put that/how it works with this PHP.
My confusion is I am not sure where the PHP is telling it to go to some blank page when you hit submit, so I don't know where to stop and start the script. I also just don't know how to mesh this all together properly. Is it in the PHP or the script where I have it check all elements before it can call to action the "thank you overlay". I just don't really know what direction to go from here.
Thank you so much for your time. I am learning a lot of this on my own so my knowledge is patchy.
Please let me know if I can help clear anything up.
-rj

Hava a look at jQuery Ajax. Usually, you throw data by the server by going to another page, so you do a "synchronous" request. The Ajax technique enables you to stay on the page, while a request is made, an "asynchronous" request. JQuery makes Ajax requests much simpler. Good luck ;)

Try adding an onclick event on #submit button and use a Javascript XMLHttpRequest object instead of action="mail.php" in the form

This is working from example, hope it can push you on correct path :)
Add this string right after submit button
<span class="status"></span>
PHP
if($mail_sent){
echo "<span class='notice'>Your message has been sent, thank you.</span>";
exit;
}else{
echo "<span class='error'>We couldn't send your message please try again, thank you.</span>";
exit;
}
And JS part to display errors
jQuery(function($) {
$("#contact-form").submit(function(){
return false;
})
$("#contact-form input[type=submit]").click(function(event){
var formerror = false;
$(this).attr('disabled', 'disabled').css({'cursor': 'auto', 'opacity': 0.5});
$('.status').fadeIn('normal').html('Loading please wait...');
$(this).closest("form").find("input, textarea").each(function(){
error = false;
switch($(this).attr('id')){
case 'name':
if($(this).val().match(/^[a-zA-Z\ \']+$/) == null || $(this).val() == "Name")
error = true;
else
error = false;
break;
case 'email':
if($(this).val().match(/^[a-zA-Z0-9_\.\-]+\#([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/) == null)
error = true;
else
error = false;
break;
case 'message':
if($(this).val().length < 4 || $(this).val() == "Type your message")
error = true;
else
error = false;
break;
}
if(error){
$(this).css('border-color', '#f00');
formerror = true;
}
});
if(formerror){
$('.status').fadeOut('normal',
function(){
$(this).html("One or more required fields are missing or invalid, please correct and resend.")
.addClass("error");
}
).fadeIn();
$(this).removeAttr('disabled').css({'cursor': 'pointer', 'opacity': 1});
event.preventDefault();
}else{
//get teh link
$.post( "contact.php", { name: $('#name').val(),
email: $('#email').val(),
website: $('#website').val(),
message: $('#message').val()
})
.done(function( data ) {
$('.status').removeClass('error').fadeIn('normal', function(){$(this).html(data)});
$("#contact-form input[type=submit]").removeAttr('disabled').css({'opacity': 1, 'cursor': 'pointer'});
});
event.preventDefault();
}
});
});

Related

php not working correctly on the enquiry/callback form but works fine on the contact form

This is confusing me any ideas as to why I only receive the telephone number (missing the name and email fields) when a form is submitted? Ive tried changing everything but i can't seem to get the other 2 fields to work when submitted.
<aside class="sidebar">
<h3 class="text-center">Request a Callback</h3>
<div class="enquiry-wrapper">
<form id="enquiry-form" method="post" action="enquiry.php" class="clearfix">
<input type="text" name="enquiry-name" id="enquiry-name" autocomplete="off" placeholder="Name ...">
<input type="email" name="enquiry-email" id="enquiry-email" autocomplete="off" placeholder="Email ...">
<input type="tel" name="tel" id="tel" autocomplete="off" placeholder="Phone Number ...">
<div class="form-submit">
<input type="submit" class="btn btn-colour" name="enquiry-submit" id="enquiry-submit" value="Send message">
</div>
<!-- form-submit end -->
</form>
<div id="enquiry-message"></div>
</div>
<!-- enquiry-wrapper end -->
</aside>
This is the enquiry.php
<?php
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$from = 'contact#rpsfm.co.uk';
// an email address that will receive the email with the output of the form
$sendTo = 'contact#rpsfm.co.uk';
// subject of the email
$subject = 'new contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('enquiry-name' => 'Name', 'enquiry-email' => 'Email', 'tel' => 'Tel');
// message that will be displayed when everything is OK :)
$okMessage = header( 'Location: http://rpsfm.co.uk/thanks1.html' );
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
?>
This is the js.
jQuery(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function() {
var e = $(this).attr("action");
$("#enquiry-message").slideUp(750, function() {
$("#enquiry-message").hide();
$("#enquiry-submit").after("").attr("disabled", "disabled");
$.post(e, {
name: $("#enquiry-name").val(),
email: $("#enquiry-email").val(),
tel: $("#tel").val()
}, function(e) {
document.getElementById("enquiry-message").innerHTML = e;
$("#enquiry-message").slideDown("slow");
$("#enquiry-form img.loader").fadeOut("slow", function() {
$(this).remove()
});
$("#enquiry-submit").removeAttr("disabled");
if (e.match("success") != null)
$("#enquiry-form").slideUp("slow")
})
});
return false
})
});
Hope I've done this right if not let me know any more info you need.
ATB
Luke
there are multiple things which make me wonder, besides that I do not understand what you are trying to accomplish.
In enquiry.php:
// message that will be displayed when everything is OK :)
$okMessage = header( 'Location: http://rpsfm.co.uk/thanks1.html' );
Taken this excerp from the manual:
The second special case is the "Location:" header. Not only does it
send this header back to the browser, but it also returns a REDIRECT
(302) status code to the browser unless the 201 or a 3xx status code
has already been set.
By passing this to a variable you are redirecting almost instantly before executing your code.
Secondly your JavaScript code does not seem to work as you desire. I think you want to send your form via AJAX, but your code is ignored, because the form is send via regular post.
event.preventDefault(); should prevent the sending of the form via regular submit.
Used like
jQuery(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function(event) {
event.preventDefault();
// [...]
});
});
I update as I come along with more issues.
Update
Please take a look at this:
$(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function(event) {
event.preventDefault();
var e = $(this).attr("action");
$("#enquiry-message").slideDown(750, function() {
$("#enquiry-message").hide();
$("#enquiry-submit").after("").attr("disabled", "disabled");
$.post(e, {
"enquiry-name": $("#enquiry-name").val(),
"enquiry-email": $("#enquiry-email").val(),
"tel": $("#tel").val()
}, function(e) {
document.getElementById("enquiry-message").innerHTML = e;
$("#enquiry-message").slideDown("slow");
$("#enquiry-form img.loader").fadeOut("slow", function() {
$(this).remove();
});
$("#enquiry-submit").removeAttr("disabled");
if (e.type === "success") {
$("#enquiry-form").slideUp("slow");
}
});
});
});
});
You have used the wrong variable names for the POST data. So your assoc array in the enquiry.php could not use the correct keys and left it out. It seems like the assignment of the header() function works, but it seems like very bad practice to me. You could return the ok message with your AJAX return call, instead of using the header() function.

PHP Mail not sending mail with AJAX [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
Good day, so I've stumbled upon this very easy problem for you pros out there. To note, I have been researching for this problem but I just don't understand why this is not working. So what I'm doing is I'm trying to make a review form successfully send a mail to my email. So here's my code:
HTML
<input type="text" id="his-name" name="his-name" placeholder="His name*">
<input type="text" id="her-name" name="her-name" placeholder="Her name*">
<input type="text" id="location" name="location" placeholder="Location of honeymoon*">
<textarea id="fav-moment" name="fav-moment" placeholder="Favorite moment during the trip"></textarea>
<textarea id="review" name="review" placeholder="Please write a short review of your experience*"></textarea>
<p>Upload few pictures from your honeymoon <span style="display: block; font-size:.7em">Please upload only a maximum of 4 photos</span></p><br/>
<form action="<?php echo get_template_directory_uri(); ?>/upload.php?sessionid=<?php echo $_SESSION['sessionid'] ?>"
class="dropzone" id="my-awesome-dropzone"></form>
JS
$(document).ready(function () {
showMenu();
$('#submit-feedback').click(function (e) {
e.preventDefault();
ajax_send_feedback();
});
function ajax_send_feedback() {
$('#contact-msg-f').html('<i style="font-size:2em;" class="fa fa-spinner fa-spin"></i>');
var errors = new Array();
errors = validate_feedback_form();
if (errors.length != 0) {
display_feedback_errors(errors);
feedbackDelivered(0);
return;
}
else {
// Send data for server validation
$.get("http://atravelduet.com/process-review-form.php", {
hisname: $('#his-name').val(),
hername: $('#her-name').val(),
location: $('#location').val(),
favmoment: $('#fav-moment').val(),
review: $('#review').val(),
url: $('#url').val()
}).done(function (response) {
if (!response) {
feedbackDelivered(1);
clearFields(); **//THIS IS NOT WORKING TOO :(**
}
else {
var errros = new Array();
errors = $.parseJSON(response);
if (errors.length != 0) {
display_feedback_errors(errors);
feedbackDelivered(0);
}
}
});
}
}
function feedbackDelivered(res) {
if (res == 1) {
$('#contact-msg-f').html('<span style="color:#00ff00;">Message Sent!</span>');
}
else {
$('#contact-msg-f').html('<span style="color:#ff0000;">Please correct the fields marked red!</span>');
}
}
PHP
<?php
$email0 = 'codeaxiscom#gmail.com';
$email1 = 'jjmaranga05#gmail.com';
$his_name = $_POST['hisname'];
$her_name = $_POST['hername'];
$location = $_POST['location'];
$fav_moment = $_POST['favmoment'];
$review = $_POST['review'];
$body = <<< EOD
<br><hr><br>
His Name: $his_name<br>
Her Name: $her_name<br>
Location: $location<br>
Favorite Moment: $fav_moment<br>
Review: $review<br>
EOD;
$headers = "From: calcutt5#box996.bluehost.com\r\n";
$headers .= "Content-type: text/html\r\n";
$emailSubject = "$his_name and $her_name Honeymoon Review";
$emailTo = $email1;
if(mail($emailTo, $emailSubject, $body, $headers))
echo "Successful";
else
echo "Unsuccessful";
?>
At first you have an error because the mail() function returns FALSE. So no email is send.
Try to put "From" header after content-type like this
$headers = "Content-type: text/html\r\n";
$headers .= "From: calcutt5#box996.bluehost.com\r\n";
And check if it is working now. If it is not try completely comment the line with From header and check if it returns success and if you get an email.
The problem maybe that you are using bad "From" header. In most cases the email should be like the domain were the mail is sent from.
In addition i suggest you use for example a PHPMailer which is not hard to configure and it works much better and you have an error log so you can easily debug it.

CMS made simple - adding a php form

I'm trying to add a PHP form to a website I'm working on. Not real familiar with PHP, but I've put the file in the upload folder in the CMS.
I think I've linked the jQuery and other files correctly and I've edited the PHP file putting in emails etc. This one also calls on another PHP validation file.
Anyway it shows up normally and I can fill it out but it goes to a 404 page and doesn't work.
My question is, what linking convention do I use to link to the php file and is it in the right place? I use cPanel where the CMS is installed.
Instead of putting: action="url([[root_url]]/uploads/scripts/form-to-email.php"
should I just put: action="uploads/scripts/form-to-email.php"?
The page in question is here: www.edelweiss-web-design.com.au/captainkilowatt/
Also, anyone know a good captcha I can integrate with it...? Thanks!
<div class="contact-form">
<h1>Contact Us</h1>
<form id="contact-form" method="POST" action="uploads/scripts/form-to-email.php">
<div class="control-group">
<label>Your Name</label>
<input class="fullname" type="text" name="fullname" />
</div>
<div class="control-group">
<label>Email</label>
<input class="email" type="text" name="email" />
</div>
<div class="control-group">
<label>Phone (optional)</label>
<input class="phone" type="text" name="phone" />
</div>
<div class="control-group">
<label>Message</label>
<textarea class="message" name="message"></textarea>
</div>
<div id="errors"></div>
<div class="control-group no-margin">
<input type="submit" name="submit" value="Submit" id="submit" />
</div>
</form>
<div id='msg_submitting'><h2>Submitting ...</h2></div>
<div id='msg_submitted'><h2>Thank you !<br> The form was submitted Successfully.</h2></div>
</div>
Here is the php:
<?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?><?php
/*
Configuration
You are to edit these configuration values. Not all of them need to be edited.
However, the first few obviously need to be edited.
EMAIL_RECIPIENTS - your email address where you want to get the form submission.
*/
$email_recipients = "contact#edelweiss-web-design.com.au";//<<=== enter your email address here
//$email_recipients = "mymanager#gmail.com,his.manager#yahoo.com"; <<=== more than one recipients like this
$visitors_email_field = 'email';//The name of the field where your user enters their email address
//This is handy when you want to reply to your users via email
//The script will set the reply-to header of the email to this email
//Leave blank if there is no email field in your form
$email_subject = "New Form submission";
$enable_auto_response = true;//Make this false if you donot want auto-response.
//Update the following auto-response to the user
$auto_response_subj = "Thanks for contacting us";
$auto_response ="
Hi
Thanks for contacting us. We will get back to you soon!
Regards
Captain Kilowatt
";
/*optional settings. better leave it as is for the first time*/
$email_from = ''; /*From address for the emails*/
$thank_you_url = 'http://www.edelweiss-web-design.com.au/captainkilowatt.html';/*URL to redirect to, after successful form submission*/
/*
This is the PHP back-end script that processes the form submission.
It first validates the input and then emails the form submission.
The variable $_POST contains the form submission data.
*/
if(!isset($_POST['submit']))
{
// note that our submit button's name is 'submit'
// We are checking whether submit button is pressed
// This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!".print_r($_POST,true);
exit;
}
require_once "http://www.edelweiss-web-design.com.au/captainkilowatt/upload/scripts/formvalidator.php";
//Setup Validations
$validator = new FormValidator();
$validator->addValidation("fullname","req","Please fill in Name");
$validator->addValidation("email","req","Please fill in Email");
//Now, validate the form
if(false == $validator->ValidateForm())
{
echo "<B>Validation Errors:</B>";
$error_hash = $validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
echo "<p>$inpname : $inp_err</p>\n";
}
exit;
}
$visitor_email='';
if(!empty($visitors_email_field))
{
$visitor_email = $_POST[$visitors_email_field];
}
if(empty($email_from))
{
$host = $_SERVER['SERVER_NAME'];
$email_from ="forms#$host";
}
$fieldtable = '';
foreach ($_POST as $field => $value)
{
if($field == 'submit')
{
continue;
}
if(is_array($value))
{
$value = implode(", ", $value);
}
$fieldtable .= "$field: $value\n";
}
$extra_info = "User's IP Address: ".$_SERVER['REMOTE_ADDR']."\n";
$email_body = "You have received a new form submission. Details below:\n$fieldtable\n $extra_info";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
#mail(/*to*/$email_recipients, $email_subject, $email_body,$headers);
//Now send an auto-response to the user who submitted the form
if($enable_auto_response == true && !empty($visitor_email))
{
$headers = "From: $email_from \r\n";
#mail(/*to*/$visitor_email, $auto_response_subj, $auto_response,$headers);
}
//done.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//This is an ajax form. So we return success as a signal of succesful processing
echo "success";
}
else
{
//This is not an ajax form. we redirect the user to a Thank you page
header('Location: '.$thank_you_url);
}
?>
I've added the php file.
So, in the action part, when I submit the form, it no longer gives me a 404 but takes me to a blank page with the 'form-to-email.php' page. However, the script is not working from what I can tell. Again, I know html and css, and little javascipt, but how php is meant to work...?
What am I doing wrong?
I would suggest using one of the modules for CMS instead of trying to build form in PHP from scratch. It is much more safer to use CMS buildin functions and that is the point of using the CMS in the first place. For CMS made simple the formbuilder module is here:
http://dev.cmsmadesimple.org/projects/formbuilder
Thanks for all the comments.
I found another form with a captcha (PHP) and preserved the whole structure by uploading it as is into CMSMS uploads folder.
I then used iframe to embed the form on my page, changed a couple of little details with the CSS and wording, and bob's your uncle, it works just fine.
For anyone interested, I used: www.html-form-guide.com/contact-form/creating-a-contact-form.html
This is free and I am certainly not trying to spam as I am in no way affiliated with this site or any sites associated with it.

PHP and AJAX: How to send/handle error responses?

There are 3 elements to this.
An HTML form
The AJAX connection which sends the form values and receives and parses response from the PHP script
The PHP script which decides whether the values are good/bad or not and sends back an appropriate response (probably in XML format for easy parsing by the javascript function?)
When the PHP looks at and handles the sent data, inserting it into a database or doing whatever with it, it needs to send back a response or maybe a collection of responses so that javascript can display a proper error message(s) to the user. Maybe also putting a red border or something around the elements that have the bad input.
How is this usually done, on both ends? I'm thinking that PHP should just send back simple numeric error codes and javascript will set the proper text error messages in different divs. But I'm not really sure, and I'm not really sure what I should be googling to find an answer.
(BTW I'm not talking about HTTP error codes)
Use this jquery ajax function to post data to php file Then do whatever with data (send in data base or make some collections ) then echo result that you will catch within success section. Then put your result in a div or where you want.
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"dummyData="+dummyData,
beforeSend: function()
{
},
success: function(resp)
{
$("#resultDiv").html(resp);
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
What you are asking is called validation.
There is server side validation, and client side validation.
The first is the most important one, as you don't want users to corrupt your database.
The second is important for your customer. As it gives him prompt response about anything that's invalid with the form (red border).
If you want to validate the form client side, it is usually done with Javascript.
For server side validation, I would use JSON, as the communication between server and client, as both php and javascript know how to handle it well.
For php:
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php
for JS.
just access the result parameter:
success: function(response){
var json = $.parseJSON(response.responseText);
}
Example for Ajax contact form: (Was originally in dutch and it's kinda old and badly coded)
Keep in mind you need jquery for this example. Just download the jquery.js from their website and add it to your scripts in the of your HTML
form.html
<form id="frm_contact" name="contactformulier">
<label>Naam<span style="color:red">*</span></label><br/>
<input type="text" size="15" maxlength="50" name="naam" />
<br/><br/>
<label>Bedrijf</label><br/>
<input type="text" size="15" maxlength="50" name="bedrijf" />
<br/><br/>
<label>Email<span style="color:red">*</span></label><br/>
<input type="text" size="15" maxlength="50" name="tmail" />
<br/><br/>
<label>Bericht<span style="color:red">*</span></label><br/>
<textarea name="tekst">
</textarea>
<br/><br/>
(<span style="color:red">*</span>) Required fields!
<br/><br/>
<div id="subbutton">Send</div>
</form>
<div id="error-msg"></div>
form.html (javascript code)
<script>
$(document).ready(function(){
var err="";
$("#subbut").click(function(){
$.post("PHP/ajax_contact.php", $("#frm_contact").serialize(),
function(data){
switch(data){
case '0':
err="<span><center>Thanks for contacting us!</center></span>";
$("#frm_contact").hide();
break;
case '1':
err="Invalid email!";
break;
case '2':
err="Fill in all fields please!";
break;
case '3':
err="Error sending this mail.";
break;
default:
err="<center>Mail server is offline.</center>"; //Or whatever error
$("#frm_contact").hide();
}
$("#error-msg").html("<br/>"+err+"<br/>");
});
});
});
</script>
PHP/ajax_contact.php
<?php
function check_email_address($email) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
}
return false;
}
$naam = trim($_POST['naam']);
$bedrijf = trim($_POST['bedrijf']);
$tmail = trim($_POST['tmail']);
$tekst = trim($_POST['tekst']);
if(isset($naam ) && isset($tmail) && isset($tekst)){
if(!empty($naam) && !empty($tmail) && !empty($tekst)){
if(check_email_address($tmail)){
$to = 'name#something.com';
$subject = 'Some subject';
$message = 'Name: '.$naam.' //// Company: '.$bedrijf.'
-------------------------------------------------------
'.$tekst.'
-------------------------------------------------------
Sended on: '.date("F j, Y, g:i a").' - from: www.somthing.com';
$headers = 'From: '. $tmail . "\r\n" .
'Reply-To: '. $tmail . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
echo '0'; //Succes <3
}else{
echo '1'; //Invalid mail adres
}
}else{
echo '2'; //Empty fields
}
}else{
echo '3'; //Fail post
}
?>

Ajax code sending form data to PHP server for validation

I'm having a difficult time implementing this AJAX code into my form so that the page doesn't need to reload but will still perform server-side validation. I'm new to AJAX and PHP, so I'm working off a couple form templates, but I have been working on this for hours and I can't figure out why it's not working. Any help would be appreciated.
Here's a portion of the HTML code:
<div id="popupContact">
<form id="formElem" name="formElem" action="" method="post">
<fieldset class="step">
<legend>Personal Details</legend>
<p>
<label for="firstname">First Name</label><em>*</em>
<input id="firstname" name="firstname" />
</p>
<p>
<label for="lastname">Last Name</label><em>*</em>
<input id="lastname" name="lastname" />
</p>
<p>* fields are required</p>
</fieldset>
<fieldset class="step">
<legend>Confirm</legend>
<p>Before you submit your information, please ensure that each step
below has this <img src="../img/global/checked.png" alt="Complete" >
above them. If there is a step that has this
<img src="../img/global/error.png" alt="Error" >, please click on that tab
and review the information to ensure it is correct and complete. Thank you.</p>
<p>
<label for="human">Please Type: "Something"</label><em>*</em>
<input id="human" name="human" />
</p>
<p class="submit">
<button id="registerButton" type="submit">Submit</button>
</p>
</fieldset>
</form>
</div>
Here's the JAVAScript code:
$(function() {
var form = $("#formElem");
var fname = $("#firstname");
var lname = $("#lastname");
var address = $("#streetaddress");
var city = $("#city");
var state = $("#state");
var phone = $('#phone');
var email = $('#email');
var insurance = $('#insurance');
var license = $('#license');
var human = $('#human');
$('#registerButton').bind('click',function(){
if($('#formElem').data('errors')){
alert('Please correct the errors in the Form');
return false;
}
else {
var dataString = 'fname='+$('#firstname').val()+'&lname='+$('#lastname').val()+'&address='+$('#streetaddress'.val())+'&city='+$('#city')+'&state='+$('#state').val()+'&phone='+$('#phone').val()+'&email='+$('#email').val()+'&insurance='+$('#insurance').val()+'&license='+$('#license').val()+'&human='+$('#human').val();
$.ajax({
type: "POST",
url: "js/validation.php",
data: dataString,
async: false,
success: function() {
$('#popupContact').html("<div id='message'></div>");
$('#message').html("<h2>Inquiry Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='..img/global/check.png' />");
});
}
});
return false;
}
});
And here's the PHP code:
<?php
if(isset($_POST['email'])) {
$email_to = "somebody#somewhere.com";
$email_subject = "Inquiry";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['firstname']) ||
!isset($_POST['lastname']) ||
!isset($_POST['email']) ||
!isset($_POST['phone']) ||
!isset($_POST['streetaddress']) ||
!isset($_POST['city']) ||
!isset($_POST['state']) ||
!isset($_POST['insurance']) ||
!isset($_POST['license']) ||
!isset($_POST['human'])){
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$firstname = $_POST['firstname']; // required
$lastname = $_POST['lastname']; // required
$emailfrom = $_POST['email']; // required
$phone = $_POST['phone']; // required
$address = $_POST['streetaddress']; //required
$city = $_POST['city']; //required
$state = $_POST['state']; //required
$insurance = $_POST['insurance']; //required
$license = $_POST['license']; //required
$human = $_POST['human']; //required
$error_message = "";
$email_exp = '/^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/';
if(!preg_match($email_exp,$emailfrom)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($firstname)."\n";
$email_message .= "Last Name: ".clean_string($lastname)."\n";
$email_message .= "Email: ".clean_string($emailfrom)."\n";
$email_message .= "Telephone: ".clean_string($phone)."\n";
$email_message .= "Address: \n".clean_string($address)."\n";
$email_message .= "".clean_string($city).", ";
$email_message .= "".clean_string($state)."\n";
$email_message .= "Have Insurance: ".clean_string($insurance)."\n";
$email_message .= "Have License: ".clean_string($license)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
I left out most of the actual validation code part of it, so I know that what you see isn't complete. What I don't understand is that without the AJAX part of this, the form validation works just fine-client and server-side, but when I add the AJAX, something's not connecting. Thanks for your help in advance.
EDIT
Does anyone have a suggestion as to where my code is going wrong?
EDIT
Okay, so if I put js/validation.php in the action="" tag for the form and disable the AJAX part of the code, then validation works just fine, but I'm forwarded to a page that is just blank with the confirmation code. Does this shed any light on the issue? Really, any help is appreciated. I've tried using the tips given in the comments, but for some reason nothing happens. It looks like my page is refreshed, but no confirmation message, or anything. I am totally and completely lost.
You're not far off, but I think I'd attack this in a slightly less aggressive manner.
Starting with the form, I'd just make it a form with an id, and park the submit button outside the form tags. Why? Because a button inside a form can have some undesirable effects (like submitting to a magical black hole) Less code = happy developer.
I'd catch the click on the button with a click handler. So:
$('#registerButton').click(function(){
Do your ajax here
});
I'd catch errors initially with front-end validation, because it saves server hits and is more pleasant from a UI standpoint. It's also faster....and no, it can't be entirely relied on because any competent person can override it, but it's a good first step. My personal favorite is here
In the click action, I'd use the ajax (like you have in your
example) to submit the form to your script for validation.
Serialize your form to send it in:
$.ajax({
type: "POST",
url: "js/validation.php",
data: $('#formElem').serialize(),
...
I'd have the script return a json string with a result case
(true/false) and data to support that case (such as an id for
success, and an array of the error cases for false) So, you're
doing exactly right with your ajax call above, but return the
data
type for my example as json (not dataString) and add a var in
the
parens after success (let's use returndata as an example) Then, within your
success callback, the returned data would be available as
returndata.field (change field to equal the variable name in the
json string) If it doesn't work, check the output on
jsonlint.com
In the success of the ajax call from step 4, setup two cases (if/else). If your result case is true, let them proceed and indicate success as your UI dictates. If the result case is false, then iterate through the array of error cases to notify the user on each respective question.
You're almost there. If this is your first experience with jQuery AJAX, I'm really impressed!
I know you already accepted an answer, but I also wanted to suggest checking out the jQuery Validate plugin - http://bassistance.de/jquery-plugins/jquery-plugin-validation/ - no need to rewrite the wheel really. I personally use this plugin anytime I'm doing any type of client-side validation with jQuery. I mention this too because the plugin comes with a native "remote" validation type that you can use for any type of remote validation with a few simple lines of code. I've also read in some places that jQuery may start "officially" supporting the validation plugin at some point, so it can never hurt to start using it sooner than later. Just some food for thought!

Categories