I have a contact form, on my personal portfolio webpage, made with PHP with a friends help (i'm a dummy when it comes to PHP.)
Although i have a problem with it. Whenever the submit button is pressed, and the mail is sent, it makes the page reload. How can i fix this?
I've copied (and changed the personal stuff) all my form, since i have no idea where or what to change:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $subject = "";
$name = $email = $comment = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid e-mail format"; }
}
if (empty($_POST["subject"])) {
$subjectErr = "Subject is required";
} else {
$subject = input($_POST["subject"]);
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = input($_POST["comment"]);
}
}
// MailGun cURL API //
$curl_post_data=array(
'from' => "$name <$email>",
'to' => 'my#mail.com',
'subject' => $subject,
'text' => $comment,
);
$service_url = 'mailgunlink.com';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "api:key-123456789123456789abc");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
// trim //
function input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<section id="kontaktformular">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row" id="kontakt">
<div class="six columns">
<label>Full Name <span class="error">*<?php echo $nameErr;?></span></label>
<input class="u-full-width" type="text" placeholder="Peter" name="name" id="navn">
</div>
<div class="six columns">
<label>Your Email <span class="error">*<?php echo $emailErr;?></span></label>
<input class="u-full-width" type="email" placeholder="Peter#Example.com" name="email" id="email">
</div>
<label>Subject <span class="error">*<?php echo $subjectErr;?></span></label>
<input class="u-full-width" type="text" placeholder="Design" name="subject" id="subject">
<label>Message <span class="error">*<?php echo $commentErr;?></span></label>
<textarea class="u-full-width" placeholder="Whatever..." name="comment" id="besked"></textarea>
</label>
<input class="button-primary change" type="submit" value="Send">
</div>
</form>
</section>
I hope the snippet is sufficient, even though it looks messy like this.
If you need more information feel free to yell at me for it.
Also, bonus question. I need the submit button to also HIDE the form (display: none; -> #kontaktformular) and SHOW another div (display: block; -> #feedbackmsg)
Thanks in advance! The first question is the most important!
I'm pretty sure that this question has already been asked and answered multiples. Either way to do it you'll have to use AJAX which is pretty simple and one way to do it is.
<section id="kontaktformular">
<form id="kontaktform" method="post">
<div class="row" id="kontakt">
<div class="six columns">
<label>Full Name <span class="error">*</span></label>
<input class="u-full-width" type="text" placeholder="Peter" name="name" id="navn">
</div>
<div class="six columns">
<label>Your Email <span class="error">*</span></label>
</div>
<label>Subject <span class="error">*</span></label>
<input class="u-full-width" type="text" placeholder="Design" name="subject" id="subject">
<label>Message <span class="error">*</span></label>
<textarea class="u-full-width" placeholder="Whatever..." name="comment" id="besked"></textarea>
</label>
<input id="kontaktform_input" class="button-primary change" type="submit" value="Send">
</div>
</form>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$("#kontaktform").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
$.ajax({
type: "POST",
data: $(this).serialize(), // serializes the form's elements.
success: function(data)
{
}
});
});
</script>
Yes AJAX is the answer you are looking for in this case:
Add an ID to the submit button eg.
<input class="button-primary change" id="Kontakt_Submit" type="submit" value="Send">
Then next in your js file write a similar code
jQuery("#Kontakt_Submit").click(function () {
//serialize the data, in simple terms for you to understand, it will
// get all the input element name value, then this data will be sent as POST DATA
var data = jQuery('form').serialize();
console.log('data-->' + data);
$.ajax({
type: 'POST',
dataType: "json",
url: 'ajax.php',
data: {
check: 'Kontakt_Form',
Kontakt_Form_Data: data
},
success: function (data) {
}
});
});
Next in your ajax.php file add this code
if ($_POST['check'] == 'Kontakt_Form') {
$result_array = array();
$extracted_Array= array(); // since we declared both the variable names as "value" in JQuery
parse_str($_POST['Kontakt_Form_Data'], $extracted_Array);
$name= $extracted_Array['name'];
$email= $extracted_Array['email'];
...//do the the other things what you need to do here, then enter in result array and return it for your output values if any.
}
Hope this will help you understand in a simple way to set up what you wanted.
Related
I'm trying to develop a contact form for a language school website that runs on Wordpress.
Disclaimer: I'm about 6 months into coding, so please forgive me for being new to this. I'm developing my own theme and I wanted to limit usage of plugins to bare minimum for safety reasons - I prefer to learn how to write stuff myself instead on relying on updates of a third-party plus the courses I follow on Wordpress dev listed it as a good practice to avoid unnecessary plugins.
Update: I tried implementing plugins, but they either broke my page or didn't work anyway.
The problem is listed below in bold.
What I want to achieve:
Simple contact form that takes following info: name, email, course, phone (optional) and a message.
Validate the form if user provided correct info - I can't make the
user provide valid info, but at least I want to lock number into
numbers only range and check if email is correct.
Check if user is human (Captcha).
Send the email to my address and provide a copy to the sender.
Inform the user whether the action was a success or a failure.
What I succeeded with:
Mail gets sent.
Captacha seems to be working and filtering out attempts that do not click on it.
What 'kinda works':
The PHP doesn't seem to validate the form. I used HTML type and require instead, but I've read that solution is not ideal. I tried to use JS to write some functions that would prevent unwanted input, but I couldn't get it to work properly. I decided to ask the question first in case it might be a dead end. JS seems to be working on my Wordpress as I'm using Bootstrap and some custom JS for certain features so I'm pretty sure the code gets executed, but I wanted to ask first if that's the correct way of approach it before I invest my time in it.
What I have a problem with:
It is imperative to me that the user gets feedback from the page whether the email has been sent or not for obvious business-client communication reasons. I tried two solutions found on SO:
Injecting JS alert into PHP's echo inside conditional (JS doesn't get executed)
Using header method to redirect into thank-you.page that informs about success or error.page that
informs about a failure and recommends another avenue of contact
What went wrong: the second solution got executed properly, the user gets redirected to site.com/thank-you or site.com/error, however the browser crashes due to 'too many redirects'.
I tried googling, I tried different solutions from tutorials. What would be your recommendation?
My code:
<?php
$nameErr = $emailErr = $courseErr = $phoneErr = "";
$name = $email = $course = $comment = $phone = "";
$thank_you = wp_redirect( '"'.home_url().'/thank-you"', 301 );
$error = wp_redirect( '"'.home_url().'/error', 301 );
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Give name";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Need email";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Email incorrect";
}
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!is_numeric($number)) {
$phoneErr = "Bad number";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["course"])) {
$courseErr = "Pick course";
} else {
$course = test_input($_POST["course"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST['g-recaptcha-response']))
{
$secret = 'mySecretKey';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
$message = "g-recaptcha verified successfully";
if(isset($_POST['submit'])){
$to = "myEmail#mail.org"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$course = $_POST['course'];
$phone = $_POST['phone'];
$comment = "Form submission";
$comment2 = "Copy of your form submission";
$message = "Name:" . $name . "Interested in " . $course. " Number" . $phone . " " . " Wrote" . "\n\n" . $_POST['comment'];
$message2 = "Copy " . $name ."\n\n" . "Interested in:" . $course . "\n\n" . $_POST['comment'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$comment,$message,$headers);
mail($from,$comment2,$message2,$headers2);
// sends a copy of the message to the sender
header($thank_you);
// This redirects to page thanking for contact.
}
else
header($error);
// This redirects to page informing about failure.
$message = "couldn't verify Captcha. Email not sent.";
echo '<script type="text/javascript">mailNotSent();</script>';
}
?>
<section id="contact" class="contact">
<div class="container pseudonest">
<div class="pseudonest contact__head--nest">
<h1 class="display-5 lh-1 mb-2 contact__head--pseudocircle contact__head--header mx-auto">Enroll now</h1>
</div>
<div class="container m-auto">
<div class="d-flex justify-content-center contact__form">
<div class="col-md-7 col-lg-8">
<form action="" method="post">
<form class="needs-validation" novalidate>
<div class="row g-3">
<div class="col">
<label for="name" id="nameHeader" class="form-label">Name</label>
<input type="text" class="form-control radio__margin" id="name" name="name"
placeholder="" value="<?php echo $name;?>" required>
<div class="invalid-feedback">
<?php echo $nameErr;?>
</div>
<label for="email" class="form-label">Email</label></label>
<input type="email" class="form-control radio__margin" id="email" name="email"
placeholder="you#example.com" value="<?php echo $email;?>" required>
<div class="invalid-feedback">
<?php echo $emailErr;?>
</div>
<label for="phone" class="form-label">Phone</label></label>
<input type="number" class="form-control radio__margin" id="phone" name="phone"
pattern="[0-9]+" placeholder="+48 111 222 333" value="<?php echo $phone;?>">
<div class="invalid-feedback">
<?php echo $phoneErr;?>
</div>
</div>
<div class="col radio__col">
<label for="firstName" class="form-label">Course?</label>
<div class="row radio__section">
<label class="radio__container">English
<input type="radio" name="course"
<?php if (isset($course) && $course=="English") echo "checked";?>
value="English">
<span class="radio__checkmark"></span>
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Polish") echo "checked";?>
value="Polish">
<span class="radio__checkmark"></span>Polish
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Italian") echo "checked";?>
value="Italian">
<span class="radio__checkmark"></span>Italian
</label>
<span class="error"> <?php echo $courseErr;?></span>
</div>
</div>
</div>
<div class="col-12 mb-5">
<label for="email-content" class="form-label">Content</label>
<div class="input-group has-validation">
<textarea class="form-control" rows="5" name="comment"
cols="30"><?php echo $comment;?></textarea>
<div class="invalid-feedback">
</div>
</div>
</div>
<form id="frmContact" action="varify_captcha.php" method="POST" novalidate="novalidate">
<div class="g-recaptcha my-3" data-sitekey="mySiteKey">
</div>
<input type="submit" name="submit" value="Send" id="submit"
class="btn btn-primary contact__form--btn">
<div id="fakeSubmit" class="btn btn-primary contact__form--btn hidden">Fill the form
</div>
</form>
</form>
</div>
</div>
</section>
I am building a basic contact form (three fields) for my site. I have the form built in HTML and CSS; all I had to do was build the PHP to make the form responses send to my email. I found a tutorial and built the PHP file (which worked), but wanted the form to submit in the background and not leave the original page. I found an online tutorial to do that using Ajax, and after some tweaking, I got it mostly to work. The only issue I'm having now is that when I receive the email with the response, the message field is coming back as "undefined."
I have a good grasp on HTML and CSS, but PHP and JS are new to me (just started learning them for this project), so any help on how to fix this issue and possibly correct any wrong code would be a huge help. I've included the form HTML, PHP, and JS below (PHP and JS are both named 'contact.[filetype]'.
HTML
<div id="contact_form">
<form name="contact" action="">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" required/>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" required/>
</div>
<div class="field">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="3"></textarea>
</div>
<ul class="actions">
<li><input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" /></li>
</ul>
</form>
</div>
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$formcontent="From: $name \n Message: $comments \n";
$recipient = "alltheladsmedia#gmail.com";
$subject = "Message From Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' target='_blank' style='text-decoration:none;color:#505050;'> Return Home</a>";
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name === "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email === "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("input#message").val();
if (message === "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
$.ajax({
type: "POST",
url: "contact.php",
data: {name:name,email:email,message:message},
success: function() {
$('#contact_form').html("<div id='success'></div>");
$('#success').html("<h2>Your message was successfully submitted!</h2>")
.append("<p>We will get back to you within 24-48 hours.</p>")
.hide()
.fadeIn(1500, function() {
$('#success');
});
}
});
return false;
});
});
In your markup the field's id is "comments" but you are looking for "message" in your JS and PHP.
you have print your mail result
if(#mail($recipient, $subject, $formcontent, $mailheader))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
Make few changes if you are using jquery 3.
Change this
$(".button").on("click", function() {
// Validation here
// Put ajax outside this block
});
Edit html form like this code.
Check the dev. tools if the action attribute is added correctly by the php.
<form id="contact" name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" >
And ajax call into this
$("#contact").on("submit", function(e) {
e.preventDefault(); // Now the page won't redirect
var url = $(this).attr("action");
// Check console if contact is printed after the form is submitted
// If contact is printed the url is right
console.log(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialiseArray(), // Found a typo here fixed
success: function() {
// Your stuffs
}
});
});
Don't put the ajax call inside the input field verification.
Let me know if you find any issue so I can fix my code.
I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?
HTML:
<form action="<?php echo htmlspecialchars($_server['php_self']);?>
, mailto:example#gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> <label for="first">First Name:</label>
<input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><span class="error"><?php echo $fnameErr;?>
</span><br/>
<label for="last">Last Name:</label>
<input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><span class="error"><?php echo $lnameErr;?>
</span><br/>
<label for="mail">Email:</label>
<input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><span class="error"><?php echo
$emailErr;?>
</span><br/>
<label for="yearLevel">Year Level:</label>
<select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
<option>Year 8</option>
<option>Year 9</option>
<option>Year 10</option>
<option>Year 11</option>
<option>Year 12</option>
<option>Uni Student</option>
<option>Other</option>
</select>
<label for"comment">Comment:</label>
<textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
</textarea><br/><br/>
<input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>
PHP:
<?php
//feedback form validation code
//start
//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";
//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "* Your first name is required!";
} else {
$firstName = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
$fnameErr = "* Only letters and white space allowed!";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "* Your last name is required!";
} else {
$lastName = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
$lnameErr = "* Only letters and white space allowed!";
}
}
if(empty($_POST["comment"])) {
$comment = "* the comment box is required!";
} else {
$comment = test_input($_post["comment"]);
}
if (empty($_POST["email"])) {
$emailErr = "* Your email is required!";
} else {
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Invalid Email Format!";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//end
?>
JS script for a confirm when the user clicks submit. so it makes sense to the form.
<script type="text/javascript">
//confrim before submitting.
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
return true;
} else {
console.log("edit!");
return false;
}
}
</script>
You couldn't add multiple actions in the form action, You should send the form to a PHP file and then after validating, send the email by PHP mail function or other libraries like PHPmailer etc.
Simple answer: No, you cannot add multiple actions for tag, how you would the distinguish between which one to choose?
If you need to select different actions according to some configuration on form choices (or whatever), use Javascript to set new action of form.
In your case, use mail PHP function to send mail from PHP script when you pass your validation.
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" name="feedbackForm" id="ff" class="feedback">
and then in PHP
mail('somebody#example.com', 'Subject', 'Body', optionalHeaders);
You can't do it, but you can call mailto inside your ask() like,
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
// add mailto here
myWindow=window.open("mailto:example#gmail.com");
myWindow.close();
return true;
} else {
console.log("edit!");
return false;
}
}
And change form action like,
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" ...>
....
</form>
I am trying to send an email with an optional attachment when a button is clicked and display the results above the form fields. I have put together the following code, but it is not working (nothing happens when I click the submit button; would like to create a fiddle but JSFiddle does not accept PHP code):
Here is the HTML:
<div id="contactSubmitResult"></div>
<div id="contactSubmitResult"></div>
<div id="contactForm">
<div class="col1">
<label for="form_firstname">Firstname <span class="required">*</span></label>
<input type="text" id="form_firstname" name="form_firstname" value="" required />
</div>
<div class="col2">
<label for="form_lastname">Lastname <span class="required">*</span></label>
<input type="text" id="form_lastname" name="form_lastname" value="" required />
</div>
<div class="col1">
<label for="form_address">Address</label>
<input type="text" id="form_address" name="form_address" value="" />
</div>
<div class="col2">
<label for="form_city">City</label>
<input type="text" id="form_city" name="form_city" value="" />
</div>
<div class="col1">
<label for="form_email">Email <span class="required">*</span></label>
<input type="email" id="form_email" name="form_email" value="" required />
</div>
<div class="col2">
<label for="form_phone">Phone <span class="required">*</span></label>
<input type="tel" id="form_phone" name="form_phone" value="" required />
</div>
<div class="col12">
<label for="form_attachment">Add Attachment</label>
<input type="file" id="form_attachment" name="form_attachment" />
</div>
<div class="col12">
<label for="form_message">Message <span class="required">*</span></label>
<textarea id="form_message" name="form_message" required></textarea>
</div>
<div class="col12">
<input type="submit" id="form_send" value="Send" formnovalidate="formnovalidate" />
</div>
</div>
Here is the JavaScript:
<script type="text/javascript" src="http://jdoe.com/js/jquery-1.11.1.min.js"></script>
<!-- validate and submit form input -->
<script type="text/javascript">
$(document).ready(function() {
matchFormFields = "#contactForm input[required], #contactForm textarea[required]";
matchContactSubmitResult = "#contactSubmitResult";
errorColor = 'red';
$("#form_send").click(function() {
var formIsValid = true;
// loop through each field and change border color to red for invalid fields
$(matchFormFields).each(function() {
$(this).css('border-color', '');
// check whether field is empty
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
// check whether email is valid
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
// submit data to server if form field contents are valid
if (formIsValid) {
// retrieve input field values to be sent to server
var post_data = new FormData();
post_data.append('form_firstname', $('input[name=form_firstname]').val());
post_data.append('form_lastname', $('input[name=form_lastname]').val());
post_data.append('form_address', $('input[name=form_address]').val());
post_data.append('form_city', $('input[name=form_city]').val());
post_data.append('form_email', $('input[name=form_email]').val());
post_data.append('form_phone', $('input[name=form_phone]').val());
post_data.append('form_attachment', $('input[name=form_attachment]')[0].files[0]);
post_data.append('form_message', $('textarea[name=form_message]').val());
// Ajax post data to server
$.ajax({
url: 'http://jdoe.com/sendContactFormEmail.php',
data: post_data,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json',
success: function(response) {
if (response.type == 'error') { // load json data from server and output message
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
// reset values in all form fields
$(matchFormFields).val('');
}
// display an animation with the form submission results
$(matchContactSubmitResult).hide().html(output).slideDown();
}
});
}
});
// reset border on entering characters in form fields
$(matchFormFields).keyup(function() {
$(this).css('border-color', '');
$(matchContactSubmitResult).slideUp();
});
});
</script>
Here is the PHP code which receives the jQuery AJAX POST request:
<?php
//$output = json_encode(array('type'=>'error', 'text' => 'Yes'));
//die($output);
include("settings.php");
$boundaryString = "generateboundaryfromthis";
$to_email = "jdoe#gmail.com";
$from_email = "noreply#jdoe.com";
$replyTo_email = "noreply#jdoe.com";
if (isset($_POST)) {
// check whether this is an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array(
'type' =>' error',
'text' => 'Ajax POST request expected.'
));
die($output); //exit script outputting json data
}
// retrieve sanitized input data
$form_firstname = filter_var($_POST["form_firstname"], FILTER_SANITIZE_STRING);
$form_lastname = filter_var($_POST["form_lastname"], FILTER_SANITIZE_STRING);
$form_address = filter_var($_POST["form_address"], FILTER_SANITIZE_STRING);
$form_city = filter_var($_POST["form_city"], FILTER_SANITIZE_STRING);
$form_email = filter_var($_POST["form_email"], FILTER_SANITIZE_EMAIL);
$form_phone = filter_var($_POST["form_phone"], FILTER_SANITIZE_NUMBER_INT);
$form_message = filter_var($_POST["form_message"], FILTER_SANITIZE_STRING);
$email_body = <<<EOT
Firstname: $form_firstname
Lastname: $form_lastname
Address: $form_address
City: $form_city
E-mail: $form_email
Phone: $form_phone
Message:
$form_message
EOT;
// retrieve attached file
$hasAttachment = false;
if (isset($_FILES["form_attachment"])) {
$hasAttachment = true;
$fileTmpName = $_FILES["form_attachment"]['tmp_name'];
$fileName = $_FILES["form_attachment"]['name'];
$fileSize = $_FILES["form_attachment"]['size'];
$fileType = $_FILES["form_attachment"]['type'];
$fileError = $_FILES["form_attachment"]['error'];
$handle = fopen($fileTmpName);
$content = fread($handle, $fileSize);
fclose($handle);
$encodedContent = chunk_split(base64_encode($content));
}
if ($hasAttachment) {
// user submitted an attachment
$boundary = md5($boundaryString);
// header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:" . $from_email . "\r\n";
$headers .= "Reply-To: " . $replyTo_email . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
// plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($email_body));
// attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $fileType; name=\"$fileName\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$fileName\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encodedContent;
} else {
// user did not submit an attachment
$headers = "From:" . $from_email . "\r\n" .
"Reply-To: " . $replyTo_email . "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $email_body;
}
$mailSentSuccessfully = mail($to_email, $subject, $body, $headers);
if ($mailSentSuccessfully) {
//$output = json_encode(array('type'=>'message', 'text' => $pageSettings->getContents("mailSentSuccess")));
$output = json_encode(array('type'=>'message', 'text' => 'Message sent.'));
die($output);
} else {
//$output = json_encode(array('type'=>'error', 'text' => $pageSettings->getContents("mailSentFailure")));
$output = json_encode(array('type'=>'error', 'text' => 'Error encountered. Message not sent.'));
die($output);
}
}
One problem: you forgot to put a html tag to
matchContactSubmitResult = "#contactSubmitResult";
add
<div id="contactSubmitResult"></div>
Here is snippet. I take the liberty to provide an alternative to success: function(){}, instead I used .done() and .fail() to provide in network or other problems. See here: jQuery.ajax() (I can't test your php code, but your jquery code works)
$(document).ready(function() {
matchFormFields = "#contactForm input[required], #contactForm textarea[required]";
matchContactSubmitResult = "#contactSubmitResult";
errorColor = 'red';
$("#form_send").click(function() {
var formIsValid = true;
// loop through each field and change border color to red for invalid fields
$(matchFormFields).each(function() {
$(this).css('border-color', '');
// check whether field is empty
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
// check whether email is valid
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
// submit data to server if form field contents are valid
if (formIsValid) {
// retrieve input field values to be sent to server
var post_data = new FormData();
post_data.append('form_firstname', $('input[name=form_firstname]').val());
post_data.append('form_lastname', $('input[name=form_lastname]').val());
post_data.append('form_address', $('input[name=form_address]').val());
post_data.append('form_city', $('input[name=form_city]').val());
post_data.append('form_email', $('input[name=form_email]').val());
post_data.append('form_phone', $('input[name=form_phone]').val());
post_data.append('form_attachment', $('input[name=form_attachment]')[0].files[0]);
post_data.append('form_message', $('textarea[name=form_message]').val());
// Ajax post data to server
$.ajax({
url: 'http://jdoe.com/sendContactFormEmail.php',
data: post_data,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json'
}) .done(function(response) {
if (response.type == 'error') { // load json data from server and output message
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
// reset values in all form fields
$(matchFormFields).val('');
}
$(matchContactSubmitResult).hide().html(output).slideDown();
}).
fail( function(response){
output = '<div class="error"> NetWork Problems</div>';
$(matchContactSubmitResult).hide().html(output).slideDown();
});
}
});
// reset border on entering characters in form fields
$(matchFormFields).keyup(function() {
$(this).css('border-color', '');
$(matchContactSubmitResult).slideUp();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contactForm">
<div class="col1">
<label for="form_firstname">Firstname <span class="required">*</span></label>
<input type="text" id="form_firstname" name="form_firstname" value="" required />
</div>
<div class="col2">
<label for="form_lastname">Lastname <span class="required">*</span></label>
<input type="text" id="form_lastname" name="form_lastname" value="" required />
</div>
<div class="col1">
<label for="form_address">Address</label>
<input type="text" id="form_address" name="form_address" value="" />
</div>
<div class="col2">
<label for="form_city">City</label>
<input type="text" id="form_city" name="form_city" value="" />
</div>
<div class="col1">
<label for="form_email">Email <span class="required">*</span></label>
<input type="email" id="form_email" name="form_email" value="" required />
</div>
<div class="col2">
<label for="form_phone">Phone <span class="required">*</span></label>
<input type="tel" id="form_phone" name="form_phone" value="" required />
</div>
<div class="col12">
<label for="form_attachment">Add Attachment</label>
<input type="file" id="form_attachment" name="form_attachment" />
</div>
<div class="col12">
<label for="form_message">Message <span class="required">*</span></label>
<textarea id="form_message" name="form_message" required></textarea>
</div>
<div class="col12">
<input type="submit" id="form_send" value="Send" formnovalidate="formnovalidate" />
</div>
</div>
<div id="contactSubmitResult"></div>
I've updated my code. There are no errors with the PHP code but when I
try to attach an attachment nothing happens. – John Sonderson
if so i think the problem is here.haven't tested but, this might help :)
var myfile=$('input[name=form_attachment]').val();
//apend the file
post_data.append('form_attachment', myfile);
I want to have server side validation. Is there a way how can I have the alert like this image whenever the user input the data like email that exist in my database, the alert will appear when I hit the sumbit button. Thanks in advance. :D
Here's my create_acc.html
<form action="create_acc.php" method="POST" id="fieldform">
<dl>
<p><dt>Email Address:</dt>
<dd>
<input type="text" name="e-mail" id="e-mail" class="text" placeholder="Your Email will be your log in" autocomplete="off">
</dd>
</p>
<p><dt>Create Password:</dt>
<dd>
<input type="password" name="password" id="password" class="text" placeholder="Remember your password" autocomplete="off">
</p>
<p>
<p><dt>Your Complete name:</dt>
<dd>
<input type="text" name="name" id="name" class="text" placeholder="Your Complete name" autocomplete="off">
</p>
<p>
<dt>
<input type="submit" value="Submit">
</dt>
</p>
</dl>
</form>
Here's my create_acc.php
<?php
session_start();
$email = $_POST['e-mail'];
$name = $_POST['name'];
$pass = $_POST['password'];
$hash = hash('sha256',$pass);
function createSalt(){
$text = md5(uniqid(rand(), true));
return substr($text,0,3);
}
$salt = createSalt();
$pass = hash('sha256',$salt.$hash);
$conn = mysqli_connect('localhost','root','','mydb');
$email = mysqli_real_escape_string($conn,$email);
$query = "INSERT INTO customers(Email,Password,Name,salt) VALUES('$email','$pass','$name','$salt')";
mysqli_query($conn,$query);
mysqli_close($conn);
header('Location: index.php');
?>
You could use ajax to do this. When the user submits the form you would send an ajax request with the form data to your php script, the script will then respond with a value that you use to deside if you should display an alert or not, here is a basic example using jquery:
$(document).ready(function() {
// catch submit events for your form
$('#your-form-id').submit(function() {
// make an ajax request to your validation script
$.ajax{(
url:'create_acc.php',
type:'POST',
data:$(this).serialize(),
dataType:'json',
success:function(response) {
if(!response.success) {
alert('Something went wrong!');
}
}
});
return false;
});
});
Then in your php script you return a code telling the client how it went:
// create_acc.php
// I assume the form only has one value 'email'
$success = false;
if(isset($_POST['email'])) {
// here you would check if the email already
// exists in the database
$query = "SELECT * FROM <table> WHERE email = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('s', $_POST['email']);
// execute the query and check if a row was returned
}
// if everything went fine you should change success to true
// return json response to client
$response = array('success' => $success);
print json_encode($response);
exit;