HTML website Javascript alert after php form submission - javascript

I have Html website. There is newsletter signup form in the html. It is processed by php script file for sending the email. After the form submission I want it back to the original page and also an alert message for "Thank you for newsletter signup"
HTML :
<div class="col-xs-12 col-sm-12 col-md-6 newsletter-form">
<form name="contactform" method="post" action="scripts/contact.php" onsubmit="return ValidateForm(contactform)">
<input type="text" name="stremail" placeholder="Your email address" ><input type="submit" value="Submit">
</form>
</div>
Javascript Validation :
function ValidateForm(Form)
{
if (Form.stremail.value == "") {
alert("Please enter \"Email\" ");
Form.stremail.focus();
return (false);
}
if ((/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(Form.stremail.value)) == false) {
alert("Invalid E-mail Address! Please re-enter.");
Form.stremail.focus();
return (false);
}
return (true);
}
PHP Script :
$stremail = $_POST["stremail"];
$to = "thebrandtgroupre#gmail.com";
$from = $stremail;
$headers = "Content-type: text/html; charset=iso-8859-1\r\n";
$headers. = "From: \"$from\" <$from>\r\nReply-To: \"$from\" <$from>\r\nX-Mailer: PHP/".phpversion();
$headers. = "BCC: luxuryproperties#gmail.com,pnparamasivan#gmail.com".
"\r\n"; //for testing purpose
$subject = "The Brandt Group Newsletter Signup";
$message = "Dear Administrator,\r\n\n";
$message = $message.
"The following information was submitted to the website:<br/><br/>";
$message = $message.
"Email Address : ".$stremail.
"<br/><br/>";
mail($to, $subject, $message, $headers);
header("Location: {$_SERVER["
HTTP_REFERER "]}");
$message2 = "Thank you for newsletter signup";
echo "<script type='text/javascript'>alert('Thank you for newsletter signup');</script>";
Any help ?

If you are using Jquery you can do like this:
HTML side
<div class="col-xs-12 col-sm-12 col-md-6 newsletter-form">
<form name="contactform" method="post">
<input type="text" class="stremail" name="stremail" placeholder="Your email address" >
<input type="submit" value="Submit">
</form>
</div>
The form action and onsubmit attributs have been removed
A class has been added on stremail input
Javascript
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(function(){
var form = $('form ');
form.submit(function(e) {
e.preventDefault();
if(ValidateForm(Form)) {
var data = {
'stremail' : $('.stremail').val()
}
$.post("scripts/contact.php", data, function(response) {
if(response.success) {
alert(response.success);
}
else {
// YOUR LOGIC WHEN ERROR OCCURED
}
});
}
});
function ValidateForm(Form) {
if (Form.stremail.value == "") {
alert("Please enter \"Email\" ");
Form.stremail.focus();
return(false);
}
if ((/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(Form.stremail.value)) == false) {
alert("Invalid E-mail Address! Please re-enter.");
Form.stremail.focus();
return (false);
}
return(true);
}
});
</script>
PHP Side
Verify $_POST data and return response by type
<?php
$response = [];
if(isset($_POST["stremail"]) && !empty($_POST["stremail"])) {
$stremail = $_POST["stremail"];
$to="thebrandtgroupre#gmail.com";
$from = $stremail;
$headers = "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .="From: \"$from\" <$from>\r\nReply-To: \"$from\" <$from>\r\nX-Mailer: PHP/".phpversion();
$headers .="BCC: luxuryproperties#gmail.com,pnparamasivan#gmail.com" . "\r\n";//for testing purpose
$subject = "The Brandt Group Newsletter Signup";
$message = "Dear Administrator,\r\n\n";
$message = $message ."The following information was submitted to the website:<br/><br/>";
$message = $message ."Email Address : ".$stremail."<br/><br/>";
mail($to,$subject,$message,$headers);
$response['success'] = "Thank you for newsletter signup";
}
else {
$response['error'] = "YOUR_ERROR_MESSAGE";
}
return $response;
?>

The alert will not happen because you have already called header to redirect the user. To accomplish your goal of a javascript popup I'd perhaps set a session variable after the email has been sent and then when you are redirected back to the signup page, assuming that it is a PHP enabled page, you can test for that session and perform the javascript alert.
<?php
/* mail handler */
session_start();
$stremail = $_POST["stremail"];
$to="thebrandtgroupre#gmail.com";
$from = $stremail;
$headers = "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: \"$from\" <$from>\r\nReply-To: \"$from\" <$from>\r\nX-Mailer: PHP/".phpversion();
$headers .= "BCC: luxuryproperties#gmail.com,pnparamasivan#gmail.com\r\n";
$subject = "The Brandt Group Newsletter Signup";
$message = "
Dear Administrator,
The following information was submitted to the website:
<br/><br/>
Email Address: {$stremail}
<br /><br />";
mail( $to, $subject, $message, $headers );
header( "Location: {$_SERVER["HTTP_REFERER"]}");
$_SESSION['mail']=true;
$message = "Thank you for newsletter signup";
?>
The signup page
<?php
session_start();
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>signup</title>
</head>
<body>
<div class="col-xs-12 col-sm-12 col-md-6 newsletter-form">
<form name="contactform" method="post" action="scripts/contact.php" onsubmit="return ValidateForm(this)">
<input type="text" name="stremail" placeholder="Your email address" />
<input type="submit" />
</form>
</div>
<?php
if( !empty( $_SESSION['mail'] ) && $_SESSION['mail']==true ){
printf('<script>alert("%s");</script>', $message );
unset( $_SESSION['mail'] );
}
?>
</body>
</html>

Related

Error when sending an email: Error Cannot POST /assets/php/form.php

I have a problem with sending an email.
I get this error
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>Cannot POST /assets/php/form.php</pre> </body> </html>
The structure of my files looks like this
dist
-asstes
--php
---form.php
index.html
In the form I have given such a path <form class="fs-13 text-uppercase" id="form" method="POST" action="assets/php/form.php">
I use the server gulp connect php and this is my taks in gulp file
// Configure the browserSync task
gulp.task('browserSync', () => {
$.connectPhp.server({}, () => {
browserSync.init({
server: {
baseDir: PATHS.dist,
proxy: '127.0.0.1:8000',
}
});
});
});
// Dev task
gulp.task('dev', ['browserSync', 'vendor', 'assets', 'html', 'sass',
gulp.watch(PATHS.src + '/assets/php/*.php', ['php', browserSync.reload]);
});
This is my js file
$('#form').submit(function(event) {
event.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
}).done(function(response) {
formMessages.text(response);
$('input[name=name]').val('');
$('input[name=email]').val('');
}).fail(function(data) {
if (data.responseText !== '') {
$('.form-status').text(data.responseText);
} else {
$('.form-status').text('ERROR');
}
});
});
and php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
if (empty($name) OR empty($email)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "email#gamil.com";
$subject = "Email";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$eamil_headers = "From: $name";
if (mail_utf8($recipient, $name, $subject, $email, $email_content, $eamil_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
function mail_utf8($recipient, $name, $subject = '(No subject)', $email, $message = '' ) {
$name = "=?UTF-8?B?".base64_encode($name)."?=";
$subject = "=?UTF-8?B?".base64_encode($subject)."?=";
$headers = "From: $name <$email>\r\n".
"MIME-Version: 1.0" . "\r\n" .
"Content-type: text/html; charset=UTF-8" . "\r\n";
return mail($recipient, $subject, $message, $headers);
}
?>
from
<form id="form" method="POST" action="assets/php/form.php">
<div class="row mb-2">
<div class="col-sm-12 col-md-12">
<div class="form-group">
<input id="first-name" class="form-control text-white" type="text" name="name">
<label for="first-name">your name?*</label>
</div>
</div>
<div class="col-sm-12 col-md-6">
<div class="form-group">
<input id="email" class="form-control text-white" type="email" name="email">
<label for="email">Your email?*</label>
</div>
</div>
<button type="submit" class="btn btn-success float-none float-md-right">Let's work together</button>
</div>
</div>
</form>
I do not know where the problem lies and why it is not sending mail
Your HTML and your server are on different ports.
You have
<form id="form" method="POST" action="assets/php/form.php">
which will go to http://localhost:3000/assets/php/form.php.
Change this action to:
<form id="form" method="POST" action="http://localhost:8000/assets/php/form.php">
which by the looks of it is your gulp server address.
When you deploy however, you will have to take it into account that it would be this.

Google Recaptcha doing strange things on iOS Safari Browser

I think my case is a bit of an oddity... I have a form that is verified by Google Recaptcha. The submit button is disabled until the recaptcha has been interacted with, using a data-callback and some JS. I was just trying out my site on my iOS device using the Safari browser, and I did the Recaptcha verification and a green check appeared, like normal. Then when I scrolled, the container div that the form was in disappeared, and then the entire form was greyed out. It seemed like it went behind the site background.
This is a screenshot of the bug:
So, I am confused to say the least. I have not been able to find any similar issues in the searches I have done. The form is integrated with PHP, here's the code:
<?php
if (isset($_REQUEST['email'])) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$recaptcha_secret = "my_secret_key_was_here";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if ($response["success"] === true) {
$to = "someemail#example.com";
$subject = "Contact Form";
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$email = $_REQUEST['email'];
$comments = $_REQUEST['comments'];
$message = "First Name: \t";
$message .= $firstname;
$message .= "\n";
$message .= "Last Name: \t";
$message .= $lastname;
$message .= "\n";
$message .= "Email: \t";
$message .= $email;
$message .= "\n";
$message .= "Message: \t";
$message .= $comments;
$message .= "\n";
mail($to, $subject, $message, "From:" . $email);
header("Location: sent.html");
} else {
header("Location: failed.html");
}
}
} else {
?>
The else opens up to the page HTML, displaying the page if the conditions are not met. Here's my script:
$(document).ready(function() {
$('#submitbutton').prop( "disabled", true ).attr('title', "Please check the catchpa before submitting the form");
});
var enableBtn = function() {
$('#submitbutton').prop( "disabled", false ).attr('title', "Submit");
}
And here's my form HTML:
<form method="post" action="new.php">
<label for="firstname">First Name:</label>
<input name="firstname" required type="text" />
<label for="lastname">Last Name:</label>
<input name="lastname" required type="text" />
<label for="email">Email Address:</label>
<input name="email" required type="email" />
<label for="comments">Message:</label>
<textarea name="comments" required></textarea>
<div class="center-captcha">
<div class="g-recaptcha" data-sitekey="my_site_key_was_here" data-callback="enableBtn"></div>
</div>
<button class="send-button" id="submitbutton">Submit</button>
</form>
Any help would be greatly appreciated.
Solved it with the answer given on this thread:
Fixed positioning/z-index issue in mobile safari
Apparently my background was being translated to the front of the page, covering up the form inputs and other content.
Adding this line fixed it:
-webkit-transform: translate3d(0,0,0);

add email validation prior to submitting on php form

I have the following simple form that I am trying to get the email validation error to
show up within the form to show the error prior to submitting.
Is there a way to do this with PHP or do I have to use JSON?
If I have to use JSON, can anyone show me how to do this?
Thanks in advance.
form.html:
<form method="post" name="form" action="form.php">
<p>Robot: <input type="text" name="robot" ></p>
<p>Name: <input type="text" name="name" ></p>
<p>Email: <input type="email" name="email"></p>
<p>Phone: <input type="telephone" name="phone"></p>
<p>Message: <textarea name="message"></textarea></p>
<p><input type="submit" value="Send Form"></p>
</form>
<div id="error"></div>
form.php
<?php
// send to and from
$to = "email#example.com";
$headers = "From: email#example.com \r\n";
$headers .= "Reply-To: email#example.com \r\n";
// form inputs
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$robot = $_POST['robot'];
// email message
$email_subject = "Web Contact Message";
$email_body =
"A message from your website contact form \n\n".
"Email: $email \n\n".
"Phone: $phone \n\n".
"From: $name \n\n".
"Message: \n".
"$message \n";
// honeypot
if($robot)
header( "Location: http://www.example.com/nothankyou.html" );
else{
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo '<div id="error">Please Enter a Valid Email</div>';
}
else
{
// send it
mail($to,$email_subject,$email_body,$headers);
header( "Location: http://www.example.com/thankyou.html" );
}
}
?>
You could try using a javascript/jquery plugin to do your front end validation (ex. http://jqueryvalidation.org/, http://bootstrapvalidator.com/). If you still wanted to keep your existing code I'd suggest something like:
First, merge your form.html to form.php
Make sure your php mailing code stays at the top of the file because php headers cannot have any output done before calling them.
<?php
if (count($_POST)) {
// send to and from
$to = "email#example.com";
$headers = "From: email#example.com \r\n";
$headers .= "Reply-To: email#example.com \r\n";
// form inputs
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$robot = $_POST['robot'];
// email message
$email_subject = "Web Contact Message";
$email_body = "A message from your website contact form \n\n" .
"Email: $email \n\n" .
"Phone: $phone \n\n" .
"From: $name \n\n" .
"Message: \n" .
"$message \n";
// honeypot
if ($robot)
header("Location: http://www.example.com/nothankyou.html");
else {
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: form.php?error=email_error");
} else {
// send it
mail($to, $email_subject, $email_body, $headers);
header("Location: http://www.example.com/thankyou.html");
}
}
}
?>
<form method="post" name="form" action="">
<p>Robot: <input type="text" name="robot" ></p>
<p>Name: <input type="text" name="name" ></p>
<p>Email: <input type="email" name="email"></p>
<p>Phone: <input type="telephone" name="phone"></p>
<p>Message: <textarea name="message"></textarea></p>
<p><input type="submit" value="Send Form"></p>
</form>
<?php
if (isset($_GET["error"]) && $_GET["error"] == "email_error") {
?>
<div id="error">Please Enter a Valid Email</div>
<?php
}

Incorrect function on php script

I have a simple contact form I'm trying to implement but I'm getting an "incorrect function" error when I try to launch it. My code below is as follows, and when I click submit, it redirects to
http://mywebsite.com/contactme.php
but with the text "Incorrect function" and that's it. My debug on firefox shows the following error:
POST http://www.mywebsite.com/v/vspfiles/contactform/contactme.php [HTTP/1.1 405 Method Not Allowed 33ms]
13:54:52.368 The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range.
The character encoding of the page must be declared in the document or in the transfer protocol.
I am using volusion software if that helps. But I have no idea if the error is in my code or because my webhost won't allow the function. Can someone give me some insight? I have tried the "contactme.php" page with and without the doctype declared. My two files are below. I do not have an "error.htm" page.
contact.html:
<!DOCTYPE html>
<html>
<head>
<title>Contact</title>
</head>
<body >
<div id="contact-area">
<form method="post" action="/v/vspfiles/contactform/contactme.php">
<h3>Contact us</h3>
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" />
<label for="City">City:</label>
<input type="text" name="City" id="City" />
<label for="Email">Email:</label>
<input type="text" name="Email" id="Email" />
<label for="Message">Message:</label><br />
<textarea name="Message" rows="20" cols="20" id="Message"></textarea>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</form>
<div style="clear: both;"></div>
</div>
</body>
</html>
contactme.php:
<?php
$EmailFrom = "email#gmail.com";
$EmailTo = "email#gmail.com";
$Subject = "contact form";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// informs user they submitted, redirects to homepage
if ($success){
alert("Thank you for your interest in our multiple sample processing system. A member of the Claremont Bio team will respond to you shortly.");
window.location.assign(location.hostname);
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
alert("Thank you for your interest in our multiple sample processing system. A member of the Claremont Bio team will respond to you shortly.");
window.location.assign(location.hostname);
This is not valid php code, it is javascript. It definitely should not be in your php script.
As an alternative, in your if($success) condition you could redirect to a "success.php" page. For example:
if($success){
header("Location: http://www.mydomain.com/success.php");
}
An example of a contact.php page I use is as follows, note as per Jorge's comments, I make use of echoing the command...
<?php
// configuration
require("../includes/config.php");
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// submission is sanitised using the "query" function
$name = check_input($_POST["name"]);
$email = check_input($_POST["email"]);
$phone = check_input($_POST["phone"]);
$message = check_input($_POST["message"]);
$category = $_POST["category"];
switch($category)
{
// do some checking here
}
// insert user into db
// Success Message
$success = "
<div class=\"row-fluid\">
<div class=\"span11\">
<div class=\"alert alert-block alert-success\" id=\"thanks\">
<h4>Got it!</h4>
<br/>
<p>I'll be in touch within 24 hours. <strong> Promise.</strong></p>
<br/>
<p>In the meantime, why not check out my Facebook page...</p>
<br/>
www.facebook.com/myfacebooksite
</div>
</div>
</div>
";
$subject = 'New Website Message!';
$mailto = 'your#email.com';
// HTML for email to send submission details
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: $name<br>
<b>Email</b>: $email<br>
<b>Phone</b>: $phone<br>
<b>Category</b>: $category<br>
<b>Message:</b>: $message<br>
";
$headers = "From: $name <$email> \r\n";
$headers .= "Reply-To: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$mailtext = "<html><body>$body</body></html>";
if (mail($mailto, $subject, $mailtext, $headers)) {
echo "$success"; // success
}
else
{
echo 'Form submission failed. Please try again...'; // failure
}
}
else
{
// else render form
redirect("/index.html");
}
?>
edit:
my contact form page has the following js:
// do the mailing
$('#contact_form').on('submit', function(e) {
e.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: post_data,
success: function(msg) {
$(form).fadeOut(200, function(){
form.html(msg).fadeIn();
});
}
});
});
Hope that helps steer you...
So turns out this isn't my error, this is my webhost. Had to call them up and they told me they don't support PHP currently. so I'm off to rewrite this is javascript. I'll give the answer to Jason as his was the most technically correct and pointed out the error. Thanks guys.

Fadeout Email Form

I am attempting to have a bootstrap contact form fade out on submit.
I am working with code I have found (which I've slightly modified to suit my needs), and I am having trouble with its implementation. I'm fairly new and I seem to have gotten quite stuck.
Here is the JS:
$('contactUs').on('submit', function mailMe(form) {
form.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader', form).html('<img src="http://domain.com/test/images/loading.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: 'http://domain.com/test/process.php', // Your form script
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
});
Here is the Form:
<form name="contactUs" onSubmit="return mailMe(this.form)" >
<div class="inputWrap">
<div class="fname">
<input class="myInput miLeft" type="text" placeholder="Name">
</div>
<div class="femail">
<input class="myInput miRight" type="text" placeholder="Email">
</div>
</div>
<div class="taWrap">
<textarea class="myTa" type="text" placeholder="Message"></textarea>
</div>
<button class="btns btn-3 btn-3g btnsx">Send</button>
</form>
And here is the process.php:
<?php
/* Configuration */
$subject = 'New Customer Email'; // Set email subject line here
$mailto = 'myemail#me.com'; // Email address to send form submission to
/* END Configuration */
$name = $_POST['name'];
$email = $_POST['email'];
$messageContent = $_POST['messageContent'];
$timestamp = date("F jS Y, h:iA.", time());
// HTML for email to send submission details
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: $name<br>
<b>Email</b>: $email<br>
<b>Message</b>: $messageContent<br>
<p>This form was submitted on <b>$timestamp</b></p>
";
// Success Message
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h3>Submission successful</h3>
<p>Thank you for taking the time to contact Shaz Construction & Design. A representative will be in contact with you shortly. If you need immediate assistance or would like to speak to someone now, please feel free to contact us directly at <strong>(415) 382-8442</strong>.</p>
</div>
</div>
";
$headers = "From: $name <$email> \r\n";
$headers .= "Reply-To: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html><body>$body</body></html>";
if (mail($mailto, $subject, $message, $headers)) {
echo "$success"; // success
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
There are a few small things you are missing:
Your jQuery selector for the form is incorrect - give your form an ID attribute of contactUs, and then use the selector $('form#contactUs'). Get rid of the name attribute on the form.
Your button element needs to be of type submit - your button currently does nothing.
You don't need the onSubmit attribute, you are already binding your form to an event in the JS.
Your input tags currently do not have any name elements on them - they are required - see http://api.jquery.com/serialize/
You try to access an attribute on the form that does not exist (action), but you don't use it, so just remove that line.
Use return false rather than preventDefault in your event handler (I couldn't get preventDefault to work. That might just be me though!)
I can't tell this because of the context of your code, but ensure that your JS is within a $('document').ready(function() { ... } block.
I think that your JS and HTML should be:
JS
$('form#contactUs').on('submit', function() {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="http://yasharsahaleh.com/test/images/loading.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: 'http://yasharsahaleh.com/test/process.php', // Your form script
data: post_data,
success: function(msg) {
$('#loader').html('');
// We know this is the form that needs fading in/out
$('form#contactUs').fadeOut(500, function(){
$('form#contactUs').html(msg).fadeIn();
});
}
});
return false;
});
HTML
<form id="contactUs">
<div class="inputWrap">
<div class="fname">
<input name="name" class="myInput miLeft" type="text" placeholder="Name">
</div>
<div class="femail">
<input name="email" class="myInput miRight" type="text" placeholder="Email">
</div>
</div>
<div class="taWrap">
<textarea name="messageContent" class="myTa" type="text" placeholder="Message"></textarea>
</div>
<button type="submit" class="btns btn-3 btn-3g btnsx">Send</button>
</form>
I made a small JSFiddle to illustrate most of this (taking out the AJAX part): http://jsfiddle.net/dualspiral/2rXas/1/
The PHP needs changing slightly, you are not actually printing out the variable contents. The body variable shoud actually be assigned:
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: " . $name . "<br>
<b>Email</b>: " . $email . "<br>
<b>Message</b>: " . $messageContent . "<br>
<p>This form was submitted on <b>" . $timestamp . "</b></p>
";
and the last lines should read:
$headers = "From: " . $name . " <" . $email . "> \r\n";
$headers .= "Reply-To: " . $email . " \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html><body>" . $body . "</body></html>";
if (mail($mailto, $subject, $message, $headers)) {
echo $success; // success
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>

Categories