Web form sending duplicate emails - php

first of all, I know this topic has been discussed in the past but I didn't manage to come to a conclusion, so any help is VERY appreciated.
I know a bit of html but I'm not a programmer, I had someone building a website for me but the web form is often sending duplicate (even 3 or 4 times) emails. I believe (assume) it has to do with people refreshing or hitting the submit button more than once. I tried to disable the 'submit' but I didn't manage to.
At this stage any fix would help. As long as I stop receiving multiple emails from senders.
I will try giving you as much information as possible.
This is the html code for the form:
<div class="form-input">
<div class="form-title">NAME</div>
<input id="form-name" type="text"></input>
</div>
<div class="form-input">
<div class="form-title">EMAIL</div>
<input id="form-email" type="text"></input>
</div>
<div class="form-input">
<div class="form-title">MESSAGE</div>
<textarea id="form-msg" type="text"></textarea>
</div>
<div class="form-input">
<div class="form-title"> </div>
<input id="form-send" type="submit" value="SEND"></input>
</div>
</div><!--end of form holder-->
<div id="details-error">Please comlete all fields and include a valid email</div>
<div id="form-sent">Thankyou for your enquiry - We will be in touch shortly!</div>
</div>
</div>
</div>
</div>
the following is the script I have:
// Contact Form Code
$('#form-send').click(function(){
var name = $('#form-name').val();
var email = $('#form-email').val();
var message = $('#form-msg').val();
var option = $('#form-select').val();
var error = 0;
if(name === '' || email === '' || message === ''){
error = 1;
$('#details-error').fadeIn(200);
}else{
$('#details-error').fadeOut(200);
}
if (!(/(.+)#(.+){2,}\.(.+){2,}/.test(email))) {
$('#details-error').fadeIn(200);
error = 1;
}
var dataString = '&option=' + option +'&name=' + name + '&email=' + email + '&text=' + message;
if (error === 0) {
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function () {
$('#details-error').fadeOut(1000);
$('#form-sent').fadeIn(1000);
}
});
return false;
}
});
});
And lastly, the mail.php:
<?php
if ($_POST) {
$name = $_POST['name'];
$email = $_POST['email'];
$text = $_POST['text'];
$option = $_POST['option'];
$headers = $option . "\r\n" . $name . "\r\n" . $email;
//send email
mail("xxx#email.net", "Mail Enquiry", $text, $headers);
}
?>

If the submit button is being pressed more than once then this may work.
Try adding the following line of code right after $('#form-send').click(function(){
$('#form-send').attr('disabled', 'disabled');
This will disable the submit button after it has been clicked once. If the page is reloaded by the user, it will be enabled.
Note: this code has not been tested.

if (error === 0) {
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function () {
$('#details-error').fadeOut(1000);
$('#form-sent').fadeIn(1000);
}
});
This portion of code in #form-send click function is what to do when the submission was successful, you could modify the submit button to disable further clicks if you feel the users are clicking submit after they already submitted the form.
$('#form-send').attr('disabled','disabled'); // only disable the #form-send and not other forms that may need to still be submitted.

You should change the input to a button:
<input id="form-send" type="submit" value="SEND"></input>
to
<button id="form-send" type="button">SEND</button>
Because otherwise the form will be submitted once through ajax and then again via the form submit/page refresh

Related

Form, AJAX and PHP

I have a simple Subscribe form that I want to get the contents of an 'email' input to post to a MySQL db using AJAX. This is successfully creating a record with the date and time but not inserting the email address.
Can anyone see what's wrong with the following please?
form.php
<form id="subscribe" action="?action=signup" method="post" data-abide>
<div class="row collapse">
<div class="large-10 large-centered columns">
<div class="row collapse postfix-radius">
<div class="small-9 columns">
<div class="email-field">
<input type="email" name="email" id="email" placeholder="Your Email Address" required>
<small style="padding-left:10px; "class="error">Please enter a valid email address</small>
</div>
</div>
<div class="small-3 columns">
<input type="submit" id="button" class="button success postfix" value="Subscribe">
</div>
</div>
</div>
</div>
</form>
<span style="display:none;" id="message"><small><i class="fa fa-check" aria-hidden="true"></i> Subscribed</small></span>
<script type="text/javascript">
$(document).ready(function(){
$('#subscribe').submit(function(){
var data = $(this).serialize();
$.ajax({
type: 'post',
url: 'subscribe_insert.php',
data: data,
success: function(data) {
$("#message").fadeIn(250);
}
});
return false;
});
});
</script>
subscribe_insert.php
<?php
include($_SERVER["DOCUMENT_ROOT"]."/dbconnect.php");
$email = mysql_real_escape_string($_POST['email']);
$date_time = date("Y-m-d H:i:s");
$sql = "INSERT INTO subscribe
(email,
date)
VALUES
('$email',
'$date_time')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Thanks,
John
$(document).ready(function(){
$('#subscribe').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data)
$.ajax({
type: 'post',
dataType: 'JSON',
url: 'subscribe_insert.php',
data: data,
success: function(data) {
$("#message").fadeIn(250);
}
});
return false;
});
});
replace your code with this then open your browser console and check if the data s getting posted
if you can see the your email there then check if the data is at the server
in you php page copy all the contents from the page and replace
<?php
echo json_encode($_POST)
?>
and once again check console this time you should see data from the server
if both are correct put your original php code back it
Check in your database that email has the correct attributes:
For exaple check that you have at least x characters allowed to be stored, check for the type of the field:
It could be int when it it really should be something like varchar
var_dump details:
form.php is ok for this purpose.
But we are going to modify the php file temporarily to check for "post" error in the email field:
<?php
include($_SERVER["DOCUMENT_ROOT"]."/dbconnect.php");
$email = mysql_real_escape_string($_POST['email']);
var_dump($email); //dump email value
/* comment this peace
$date_time = date("Y-m-d H:i:s");
$sql = "INSERT INTO subscribe
(email,
date)
VALUES
('$email',
'$date_time')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
*/
?>
Now follow the next steps:
Open chrome
Open your webpage
Hit F12
Check the "Log XMLHttpRequests" checkbox
Send your form and you will se something in the console like: XHR finished loading: POST http://localhost//folder/subscribe_insert.php
Click the logged url of your console
You may see a list of resources (depends of your project)
Click the one that has the subscribe_insert.php title
To your right you will see some tabs click response
If there was some error or some data was echoed from that file (In this case our var_dump) you will see it there.
If you see the email actually printing out It might be a database problem as I started tellong you.
I know there are too many steps but it's very fast to do it, I hope I have helped you, greeting!

Form Button Refreshes on Click - One page Website

I've created a contact form so that users can send us an email. However, every time I click to send the email it also refreshes the page when clicked. This is a one page website.
I've attempted the fixes suggested in: How do I make an HTML button not reload the page
by using either the <button> element or use an <input type="button"/>. and also the fixes suggested in: prevent refresh of page when button inside form clicked
by adding onclick="return false;".
Both of these fixes stop the button from refreshing the page when it is clicked, however, it also stops the contact form from actually working and no longer sends an email to us.
I also updated my PHP to reflect the name changes of the type.
My PHP is:
<?php
if(isset($_POST['submit'])){
$to = "example#example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
}
?>
My HTML is:
<form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>
This currently works for sending the email, but does not stop it from refreshing the page. Would appreciate any help as to why it is doing this..
EDIT:
I've tried a few different options using AJAX since it was suggested this was the best route to take. All successfully stopped the page from refreshing, but all the options once again, stopped my contact form from working. I tried:
1:
$(function() {
$('#contactForm').on('submit', function(e) {
$.post('index.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
2:
$("#contactForm").submit(function(e) {
e.preventDefault();
});
3:
I also tried the answer offered to me by Harsh Panchal.
You can try using jquery ajax method
Create New File for send Email and in form attribute to give any id
<script>
$('#main-contact-form').submit(function(event){
event.preventDefault();
$.ajax({
type:'post',
url:'sendememail.php',
data:$(this).serialize(),
success:function(response){
if(response==1)
{
setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-success">Review Successfully Submited......</div></center></h5>');},5);
}
else
{
setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-danger">Sorry Your Review Not Submit......</div></center></h5>');},5);
}
}
});
});
</script>
#thickguru, don't expect to receive a working solution - with or without ajax - if you maintain your mail sending php code on the SAME page with the <form>...</form>. Even if the page does not refresh, then even if you are using ajax, the page must be rebuilded from the ajax results (which is a BAD option). So, you must separate the two tasks in DIFFERENT pages and only after that use ajax. In this way you achieve a beautiful "separation of concerns" (see Separation of concerns - at least the first paragraph).
Here are two options of submitting the form by using ajax.
1. Submit the form using 'json' data type (recommended):
Page "send_mail.php":
NOTA BENE: No more if(isset($_POST['submit'])){...}. If you use this validation it will fail, because, by default, the submit button will NOT be sent as part of the POST variables. You would have to manually assign it as property in the sent data object if you'd want to still validate the $_POST array.
Notice the use of the json encoding function json_encode.
<?php
$to = "example#example.com"; // this is your Email address
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo json_encode($message);
?>
Page "index.html":
NOTA BENE: No onclick attribute on submit button!
<div id="results"></div>
<form id="contactForm" name="contactForm" action="send_mail.php" method="post">
<!-- ... The form inputs ... -->
<button type="submit" id="submit" name="submit">Submit</button>
</form>
Page "index.js" (e.g your file with the js scripts):
/**
* On document ready.
*
* #return void
*/
$(document).ready(function () {
sendEmail();
});
/**
* Send email.
*
* #return void
*/
function sendEmail() {
var contactForm = $('#contactForm');
var results = $('#results');
contactForm.submit(function (event) {
var ajax = $.ajax({
method: 'post',
dataType: 'json',
url: 'send_mail.php',
data: contactForm.serialize()
});
ajax.done(function (response, textStatus, jqXHR) {
results.html(response);
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
results.html('Email sending failed!');
});
ajax.always(function (response, textStatus, jqXHR) {
// ...
});
return false;
});
}
NOTA BENE: If you decide to use form submit validation, you have to handle ALL situations. For example, when you use it like this, you will receive an error:
if (isset($_POST['submit'])) {
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo json_encode('Hello, World!');
}
The solution is to handle the not-is-set POST 'submit' as well:
if (isset($_POST['submit'])) {
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo json_encode('Hello, World!');
} else {
echo json_encode('Submit button not recognized');
}
2. Submit the form using 'html' data type:
Page "send_mail.php":
NOTA BENE: dito.
<?php
$to = "example#example.com"; // this is your Email address
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo $message;
?>
Page "index.html":
NOTA BENE: dito.
<div id="results"></div>
<form id="contactForm" name="contactForm" action="send_mail.php" method="post">
<!-- ... The form inputs ... -->
<button type="submit" id="submit" name="submit">Submit</button>
</form>
Page "index.js":
/**
* On document ready.
*
* #return void
*/
$(document).ready(function () {
sendEmail();
});
/**
* Send email.
*
* #return void
*/
function sendEmail() {
var contactForm = $('#contactForm');
var results = $('#results');
contactForm.submit(function (event) {
var ajax = $.ajax({
method: 'post',
dataType: 'html',
url: 'send_mail.php',
data: contactForm.serialize()
});
ajax.done(function (response, textStatus, jqXHR) {
results.html(response);
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
results.html('Email sending failed!');
});
ajax.always(function (response, textStatus, jqXHR) {
// ...
});
return false;
});
}
I suggest you to not use the short-hand ajax version of post or get. You have more flexibility with a normal ajax call.
Good luck!
For doing it in ajax, remove the form.action="" because it will reload the page.
Try
remove the action attribute from form.
remove the type=submit from button.
add the click event handler to button instead of adding it to form.submit.
The code will look like this
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button id="submit" name="submit">Send Message</button>
</form>
jQuery
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.post('index.php', $("form#contactForm").serialize(), function(data) {}).error(function(xhr) {alert(xhr)});
});
});
Use jQuery AJAX form submit and also Event.preventDefault(), so that page is not refreshed further.
for more help here is the link https://api.jquery.com/jquery.post/
I think jQuery and AJAX is the way to go. I have a couple suggestions:
Try moving the e.preventDefault() to before you do $.post. This should stop the event before it can reload the page and then send the email.
Try using e.stopPropagation() in addition to or instead of e.preventDefault(). This will stop the event from bubbling up the DOM so that other elements won't trigger the reload.
Try adding return false; to the end of the function. There was a similar question where this worked: Prevent form redirect OR refresh on submit?

Ajax not capturing php contact form script

I have a contact form on my website that is not posting the success or error message as it should.
The weird thing is I have used this exact same form, php, and ajax script on several other sites and it works great. In fact, it used to work great on the site in question.
The website is https://www.pouncingfoxdesign.com. The contact form is at the bottom. Feel free to fill it out for testing purposes.
Here's the form and script:
<div class="col-md-8 col-sm-9 wow form1 fadeInLeft">
<div class="contact-form clearfix contactForm">
<form id="form" action="php/email.php" class="contactForm"
method="post">
<div class="messages"></div>
<div class="input-field">
<input type="text" class="form-control" name="name"
placeholder="Your Name" required="">
</div>
<div class="input-field">
<input type="email" class="form-control"
name="email" placeholder="Your Email" required="">
</div>
<div class="input-field message">
<textarea name="message" class="form-control"
placeholder="Your Message" required=""></textarea>
</div>
<input type="submit" name="submit" class="btn btn-blue
pull-right" value="SEND MESSAGE" id="msg-submit">
<div class="g-recaptcha fadeInLeft" data-
sitekey=""></div>
</form>
</div> <!-- end .contact-form -->
</div> <!-- .col-md-8 -->
<script> $('#form').on('submit', function(e) {
event.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="img/forms/loading.gif" />
Please Wait...');
$.ajax({
type: 'POST',
url: 'php/email.php', // Your form script
data: post_data,
success: function(msg) {
var old_html = form.html()
$(form)
.html(msg).fadeIn();
setTimeout(function(){
$(form)
.html(old_html).fadeIn();
}, 4000);
},
error: function(xhr, ajaxOptions, err){
var old_html = form.html()
$(form).fadeOut(500)
.html("<h3>There was an error. Please try again.
</h3>").fadeIn();
setTimeout(function(){
$(form).fadeOut(500)
.html(old_html).fadeIn();
}, 3000);
}
});
});
</script>
And here's the PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h1>Submission successful</h1>
<h3>Thank you for contacting us!</h3>
</div>
</div>";
$to = "email#email.com";
$subject = "$name\n filled Pouncing Fox Desing Form";
$txt = "From: $name\n E-Mail: $email\n Comments:\n $message";
$headers = "From: Pouncing Fox Design" . "\r\n" ;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents
("https://www.google.com/recaptcha/api/siteverify?
secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if (mail($to, $subject, $txt, $headers)) {
echo "$success"
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
What I want it to do is replace the form with the success message for a few seconds and then go back to the form. What it does instead is just go to the email.php file with the success message being all that's on the screen.
If you want to check out https://www.mooreengaging.com, the same script and php file is used for that site. It works great and you can see my intended results. Again, feel free to fill out the form for testing purposes.
I have tried to use other ajax scripts and have tried to rework it several different times, but no matter what when clicking submit it just loads the php file. It's like it is bypassing the ajax script altogether.
Thanks!
EDIT:
I have received the emails from you guys testing and they look right. So it is working, just not posting the success message as I'd like.
Ok, I figured it out. I added <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> to the top of the page under the header.
I thought it was best to put jquery at the bottom?
Did it fail because I was trying to run that script before it loaded jquery?
Change
$('#form').on('submit', function(e)
To
$('#form').on('submit', function(event)
Because you use
event.preventDefault();

PHP+JQuery+AJAX Form not getting resubmitted with different values

This is embarrassing but I cant seem to figure out why my form wont repost after changing the values.
To be clearer, I have this password recovery form in which user enters the email address. The form is processed in PHP through AJAX and a validation/success message is displayed on the form page.
The issue here is that if the user has entered an invalid email address, it displays the error message but if the user then corrects the email address and tries to submit again, it doesn't process the input unless if the page is explicitly refreshed (in which case it shows the resubmission warning which is very annoying). Is there some property that sets the form and needs to be 'un-set' through code? How can I improve this experience? I have posted the code below.
<form id="pwd_rec_form" method="post" action="">
<div class="row">
<div class="large-6 columns">
<input type="email" required placeholder="Email ID" name="email"/>
</div>
</div>
<div id="val_msg" class="row"></div>
<div class="row">
<div class="large-6 columns">
<input id="submit_button" type="submit" value="Send" class="button"/>
</div>
</div>
<div class="row">
<div class="large-6 columns">
Back to login page
</div>
</div>
</form>
<script>
$(function()
{
$("#pwd_rec_form").submit(function()
{
var formdata = $(this).serializeArray();
var hideMsg = function() {$("#val_msg").hide()};
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "recover-password.php",
data: formdata,
success: function(res)
{
$('#val_msg').html(res);
setTimeout(hideMsg, 5000);
}
});
$("#pwd_rec_form").trigger("reset");
return false;
});
});
</script>
PHP :
<?php
include 'db-connect.php';
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$conn = getDBConnection();
// Check connection
if (mysqli_connect_errno())
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_connect_error() . '
</div>'
);
exit();
}
$eID = mysqli_real_escape_string($conn, trim(strip_tags($_POST['email'])));
$query = 'SELECT password FROM member_login WHERE email_id = "' . $eID . '";';
$result = mysqli_query($conn, $query);
if($result == FALSE)
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_error($conn) . '
</div>'
);
}
else
{
if(mysqli_num_rows($result) == 0) // User not found.
{
echo('<small class="error">This email address is not registered with us.</small>');
}
else
{
$pswd = mysqli_fetch_assoc($result);
//mail the pswd
echo(' <div data-alert class="alert-box success">
Your password has been successfully sent to your registered email address.
</div>'
);
/* free result set */
mysqli_free_result($result);
}
}
mysqli_close($conn);
}
?>
I think your problem is that you have a submit button, which automatically submits the form and refreshes the page, so your javascript doesn't get used. Try making your submit button a type="button" and then changing your jQuery to $("#pwd_rec_form").click(function() and see if that works.
You could hook the form submit, or if you wanted you can hook the click event of the submit button, prevent the default action and instead do your javascript code. Here is an example hooking the "submit_button" click event:
$(document).ready(function() {
$("#submit_button").click(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
Alternative you can do this:
$(document).ready(function() {
$(form).submit(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
The code above just hooks the form on the submit request, prevents the default action, and then you slap your ajax code in there.
I appreciate your help guys. I knew it was something silly. Turns out the form was getting processed but the validation/success messages were not being displayed as the div element that I was hiding using javascript during the first submission needed to be shown again for the second attempt!
Could you try this :
<script>
$(document).ready(function(){
$('#pwd_rec_form').on('submit', function(e){
e.preventDefault();
// insert AJAX call
});
It worked for me, the event is trigged on each click.
Best regards,

AJAX/PHP/JQUERY mailing contact form gives correct error message when nothing is in form but fails to run Ajax

I'm following the following tutorial to place a form on my website using PHP, AJAX, and JQUERY that will send the form information to my email:
http://www.spruce.it/noise/simple-ajax-contact-form/
The problem is, when I have the jquery outside the document ready I get no message at all, and when I place it in the document ready i get the error text, but when there is information in the fields nothing happens at all. Please, can someone look and see what might be the problem with my html, jquery, php, or AJAX? I'm about to pull out all of my hair. I'm testing it in Wampserver.
The HTML file is in the root directory with the PHP file. In the root directory there is a folder called "includes" that the Javascript is in. Here is the relevant code for each:
HTML:
<form id="repairform" method="post">
<p id="p1">Name:</p>
<input id="one" type="text" name="name" />
<p id="p2">How would you prefer to be reached?: </p>
<select id="two" name="Contact methods">
<option value="Phone">Email</option>
<option value="Email">Phone</option>
</select>
<p id="p3">What kind of computer are you having trouble with?</p>
<p id="p3-2">Give as much or as little info. as you'd like.</p>
<p id="p3-3">(Laptop PC, desktop Macintosh, etc)</p>
<textarea id="four" name="pc type" rows="3" cols="30"></textarea>
<p id="p4">What problems are you having with your computer/ what needs to be fixed?</p>
<textarea id="five" name="problem" rows="5" cols="30"></textarea>
<input id="three" type="submit" value="Submit Request" />
<p id="p5">What is your Email?</p>
<input id="six" type="text" name="Email/Phone" />
<p id="p7">What is your Phone Number?</p>
<input id="eight" type="text" name="Email/Phone2" />
<p id="p6">What time of day would you prefer to be reached?</p>
<input id="seven" type="text" name="Preferred Contact Time" />
</form>
JQuery:
$(document).ready(function () {
$("#repairform").submit(function (e) {
e.preventDefault();
if (!$("#six").val()) {
$("#six").val("shanew#ufl.edu");
}
var name = $("#one").val();
var email = $("#six").val();
var text = $("#five").val();
var reachpreference = $("#two").val();
var computertype = $("#four").val();
var phonenumber = $("#eight").val();
var timeofday = $("#seven").val();
var dataString = 'name=' + name + '&email=' + email + '&text=' + text
+ '&reachpreference=' + reachpreference + '&computertype=' + computertype
+ '&phonenumber=' + phonenumber + '&timeofday=' + timeofday;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (text.length > 2) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "../functions.php",
data: dataString,
success: function () {
alert("Thank you! Your message has been delivered. I will be back with you shortly");
}
});
} else {
alert("Some of the form information was not filled out correctly. Ensure all of the correct fields are filled out.");
}
return false;
});
PHP:
<?php
// Email Submit
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text'])){
//send email
mail("shanew#ufl.edu", "Contact Form: ".$_POST['name'],
$_POST['text'], $_POST['reachpreference'], $_POST['computertype']
$_POST['phonenumber'], $_POST['timeofday'], "From:" . $_POST['email']);
}
?>
Use
data: $('#repairform').serializeArray()
instead of the datastring object you're creating.
The datastring will be treated as a String, and you'll never be able to access it using $_POST['text'] and all. You may try using using $_GET instead. The datastring will be accessible that way only.
I think you miss some of closing branch });
And I think you should use name attribute for variable name that will be used in php..
<form id="theForm">
<input type="text" name="email" />
</form>
and in javascript you can use serialize so less line and easier to read.
$.ajax({
type:'POST'
url:'../functions.php'
data:$('#theForm').serialize();
})
and in php
echo $_POST['email']

Categories