The contact form doesnt work
Here is the code im using in the page.
Jquery in Index.html
<!--contact form -->
<script type="text/javascript">
$(document).ready(function(){
$('#send_message').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut.
The only difference from these checks is the email checking, we have
email.indexOf('#') which checks if there is # in the email input field.
This javascript function will return -1 if no occurence have been found.*/
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("send_email.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#cf_submit_p').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
</script>
Here is the HTML Code for the Container
Contact-Form in HTML # index.html
<!--contact form -->
<div id="contact-form">
<div id="contact_form_holder">
<form action="index.php" method="post" id="contact_form">
<p>
Your Name:
<input name="name" class="field" id="name" type="text">
</p><div id="name_error" class="error"><img src="web_files/error.png"> Please enter your name</div>
<p></p>
<p>
Your Email:
</p><div><input name="email" class="field" id="email" type="text">
<div id="email_error" class="error"><img src="web_files/error.png"> OOps!! i can't get back to you in this mail id</div>
</div>
<p></p>
<p>
The Message:
</p><div>
<textarea name="message" class="field" id="message"></textarea>
<div id="message_error" class="error"><img src="web_files/error.png"> Forgot why you came here?</div></div>
<p></p>
<div id="mail_success" class="success"><img src="web_files/success.png"> Thank you. The mailman is on his way.</div>
<div id="mail_fail" class="error"><img src="web_files/error.png"> Sorry, don't know what happened. Try later.</div>
<p id="cf_submit_p">
<!--<input type='submit' id='send_message' value='Send it to me' class="submit"> -->
<input id="send_message" value="Send The Message" class="submit" type="submit">
</p>
</form>
</div>
</div>
<!--contact form -->
And at last here is the PHP code as
send_email.php
//we need to get our variables first
$email_to = 'mail#mail.com'<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l=document.getElementById("__cf_email__"); a=l.className;if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2) {c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s); l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>';
//the address to which the email will be sent
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
/*the $header variable is for the additional headers in the mail function,
we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
That way when we want to reply the email gmail(or yahoo or hotmail...) will know
who are we replying to. */
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
}else{
echo 'failed';// ... or this one to tell it that it wasn't sent
}
Your error is at your first line in your PHP-code:
$email_to = 'email#email.com'<script type="text/javascript">
Your string ends after the e-mail address. Correct it to
$email_to = 'email#email.com';
and you should be fine.
Also, what is the JavaScript doing inside the PHP? Remove it or make sure to either echo it, or place it outside of your PHP-tags.
1)Change the first line of your php code to
$email_to = 'some.person#example.com';
2)Remove the JavaScript from the PHP file.
If its still not working, change all the $_POST to $_GET and enter the values of the variables yourself. Then run the code and tell me the output.
EDIT :
I have found your error. You have not opened your php file correctly.
http://www.justyesh.in/send_email.php
You begin PHP with <?php and close it with ?>
Related
I have set up a page that is still in construction and i'm building a webform for users to contact me.
When i fill the webform and hit the "send" button, message gets send succesfully and i receieve it on my mail...but when i hit the "send" button, i get re-directed off page, saying it was sent successfully.
How can i prompt user that the message was sent successfully, without getting redirected of page, and get the message in same window?
This is my HTML code
<form action="assets/php/contactUs.php" id="contact" class="form" role="form" method="post">
<div class="row">
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="name" name="name" placeholder="Name" type="text" required />
</div>
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required />
</div>
</div>
<textarea class="form-control" id="message" name="message" placeholder="Message" rows="5"></textarea>
<div class="row">
<div class="col-xs-12 col-md-12">
<button class="btn btn btn-lg">Send Message</button>
</div>
</div>
</form>
And this is my contactUs.php code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$message = <<<EMAIL
$message
From: $name
My email is: $email
EMAIL;
$to = "mymail#mymail.com";
$subject = "New Customer Enquiry";
mail($to, $subject, $message, "From: " . $email);
echo "Thank you, your message has been successfully sent!";
?>
AJAX
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('.btn-lg').click(function(){
$.post( "assets/php/contactUs.php", $( "#contact" ).serialize(), function(msg){
alert(msg);
} );
});
});
</script>
This is a result of successfully sent message.
Please guys help me out! Thanks!
REDIRECT OPTION
$firstpageurl = 'http://example.com';
echo "Your message has been successfully sent!";
$header('Location: '.$firstpageurl);
Use Ajax as below.Change the submit type button to a normal button by removing the type attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('.btn-lg').click(function(event){
$.post( "config.php", $( "#contact" ).serialize(), function(msg){
alert(msg);
} );
event.preventDefault();
});
});
</script>
The action part of your form tag is "assets/php/contactUs.php"
<form action="assets/php/contactUs.php" id="contact" class="form" role="form" method="post">
That means that posting this form will bring you to that page. You can either code that page to send the email and redirect them back like this...
header('Location: '.$firstpageurl);
or put the php code into this first page and remove the entire action property. If you put the php on this page, you need to wrap your code in an if so that people can load the page before posting the form.
if (isset($_POST['email'])){
echo "Sent email";
[email send code here]
}
as for putting the message saying it's sent...that will only work with the second method. To do it without a full page load at all do it with ajax.
You want to use JQuery for that.
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#contact").submit(function(){
var form_data=$("form").serialize();
$.post( "assets/php/contactUs.php",form_data, function( data ) {
alert(data);
});
event.preventDefault();
});
</script>
You can do it without using Javascript. Do the following:
Set the form to post to itself (e.g. if your form was on index.php, set action="index.php"
When the page loads, check $_POST to see if the form values were sent.
If the $_POST values are empty, display the form
If the $_POST values are set, do what you need to do with those values, then output your results into the page.
Here's a really simple example demonstrating what I mean.
<?php
$submitted = false;
if (isset($_POST["myinput"]) && $_POST["myinput"] != '') {
$submitted = true;
}
?>
<?php
if ($submitted == false) {
?>
<form action="index.php" method="post">
<input name="myinput"><input type="submit">
</form>
<?php } else { ?>
<h1>Form Submitted</h1>
<?php } ?>
Right now, whenever I click the submit button on the contact form on my website, it brings me to the page www.mysite.com/php/function/email.php, rather than running the email.php in the background like I want it to.
The website is supposed to allow you to submit the contact form, then the button will fade away and fade in a "Your message has been sent!", then fade back the button.
HTML:
<form name="contact form" id='contact_form' method="post" action="php/function/email.php">
<div class="row half">
<div class="6u">
<input name="name" placeholder="Name" type="text" class="text" />
</div>
<div class="6u">
<input name="email" placeholder="Email" type="email" class="text" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" placeholder="Message"></textarea>
</div>
</div>
<div class="row half">
<div class="12u">
<input id="submit" name="submit" type="submit" value="Send Message" class="button button-icon icon icon-envelope" />
</div>
</div>
<p id="success" style="display:none">Your message has been sent! I'll get back to you soon!</p>
<p id="error" style="display:none">Please fill in all the fields and try again!</p>
JS:
$(document).ready(function(){
$('#send_message').click(function(e){
//Stop form submission & check the validation
e.preventDefault();
// Variable declaration
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
// Disable submit button just after the form processed 1st time successfully.
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("email.php", $("#contact_form").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
//If the email is sent successfully, remove the submit button
$('#submit').remove();
//Display the success message
$('#success').fadeIn(500);
}else{
//Display the error message
$('#error').fadeIn(500);
// Enable the submit button again
$('#submit').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
};
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: Example';
$to = 'example#gmail.com';
$subject = 'Example Contact Form';
$body = "
From: $name
Email: $email
---------------
Message: \n
$message";
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $from)) {
echo 'sent';
} else {
echo 'failed';
}
}
?>
The .click() event of a <input type="submit"> isn't actually what causes the redirection. It instead becomes a .submit() event at the <form>.
You can either e.stopPropagation() so it doesn't reach the <form>.
//Stop form submission & check the validation
e.stopPropagation();
Or preventDefault() of the <form>'s .submit().
$('#contact_form').submit(function (e) {
e.preventDefault();
});
Note: You should also consider moving your code into a .submit() handler as most browsers support other ways of submitting a <form> than actually clicking the <input type="submit">.
The problem is that you're looking for click events on #send_message but your submit button has an id of submit. So that click event never happens.
So i managed to create an ajax form with jquery validation and I need to enchance it with php validation. Here is the code:
<!-- Contact form -->
<div id='contact_form_holder'>
<form action='index.php' method='post' id='contact_form'>
<p>
Your Name:
<div id='name_error' class='error'><img src='images/error.png'> Please enter your Name.</div>
<div><input class="textbox" type='text' name='name' id='name'></div>
</p>
<p>
Your Email:
<div id='email_error' class='error'><img src='images/error.png'> Please enter a valid Email.</div>
<div><input class="textbox" type='text' name='email' id='email'></div>
</p>
<p>
The Subject:
<div id='subject_error' class='error'><img src='images/error.png'> What is the purpose of the contact?</div>
<div><input class="textbox" type='text' name='subject' id='subject'></div>
</p>
<p>
The Message:
<div id='message_error' class='error'><img src='images/error.png'> Forgot why you came here?</div>
<div><textarea class="textbox" name='message' id='message'></textarea></div>
</p>
<div id='mail_success' class='success'><img src='images/success.png'> Your email has been submitted.Thank you.</div>
<div id='mail_fail' class='error'><img src='images/error.png'> There seems to be an internal error.Try later.</div>
<p id='cf_submit_p'>
<input class="button" type='submit' id='send_message' value='Send The Message'>
</p>
</form>
</div>
<!-- /Contact form -->
The send mail php code
$email_to = 'admin#localhost.com'; //the address to which the email will be sent
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
/*the $header variable is for the additional headers in the mail function,
we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
That way when we want to reply the email gmail(or yahoo or hotmail...) will know
who are we replying to. */
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
}else{
echo 'failed';// ... or this one to tell it that it wasn't sent
}
?>
And the jquery :
/// Contact Form ///
$(document).ready(function(){
$('#send_message').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
var re = new RegExp(/^[a-z0-9_\-]+(\.[_a-z0-9\-]+)*#([_a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/);
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut.
The only difference from these checks is the email checking, we have
email.indexOf('#') which checks if there is # in the email input field.
This javascript function will return -1 if no occurence have been found.*/
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.lenght == 0 || !email.match(re)) {
var error = true;
$('#email_error').fadeIn(500);
} else {
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
}else{
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("send_email.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#cf_submit_p').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
$(':input','#contact_form')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
});
}
});
});
I have a very poor knowledge of php and I really need someone to help me validate this form with php if javascript is disabled and output the errors inside the correspoding error divs the jquery uses. Help would really be appreciated!
on index.php check values of your html fields
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if($_REQUEST['name']!="" && $_REQUEST['email']!="" && $_REQUEST['subject'] !="" && $_REQUEST['message']!="")
{
if (preg_match($regex, $_REQUEST['email'])) {
echo $email . \" is a valid email. We can accept it.\";
} else {
echo $email . \" is an invalid email. Please try again.\";
}
}
else{
echo "Error";
}
try to pass an error code to the page with the form via Redirection
http://example.com/form.php?error=1
and check the $_GET["error"] for the error code, display the message that is associated with the error where you want in the page
I'm having one, admittedly very minor issue with a contact form I've set up in WordPress using jQuery, jQuery form and PHP Mail to send a form-generated email.
To replace my current contact form which performs a pHp validation from within the contact form page and then sends using PHP Mail, I've designed the following simple html 5 form (which can be seen on this page: http://edge.donaldjenkins.net/contact):
<form id="contact" method="post" action="">
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" placeholder="Your Name" title="Enter your name" class="required">
<label for="email">E-mail</label>
<input type="email" name="email" placeholder="yourname#domain.com" title="Enter your e-mail address" class="required email">
<label for="phone">Phone</label>
<input type="tel" name="phone" placeholder="ex. (555) 555-5555">
<label for="website">Website</label>
<input type="url" name="url" placeholder="http://">
<label for="message">Question/Message</label>
<textarea name="message"></textarea>
<label for="checking" class="hidden">If you want to submit this form, do not enter anything in this field</label><input type="text" name="checking" class="hidden">
<input type="submit" name="submit" class="button" id="submit" value="Send Message" />
</fieldset>
I then use the jQuery validate [jquery.validate.js] and form [jquery.form.js] plugins to perform a client-end validation:
<script src="js/jquery.validate.js"></script>
<script src="js/jquery.form.js"></script>
<script>
$(function(){
$('#contact').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
url: 'send-message.php',
success: function() {
$('#contact').hide();
$('#instructions').hide();
$('#status').show();
$('#popular-posts').show();
$('#status').append("<p>Thanks! Your request has been sent. One will try to get back to you as soon as possible.</p>")
}
});
}
});
});
</script>
After the validation, the above script uses jQuery.form's ajaxSubmit function to submit the date to a server PHP page, send-message.php (the reason being that javascript can't send email). I use this PHP file to carry out a second, server-side validation of the data (though this is probably redundant, since because the setup relies on javascript to pass the data on to the server, one can safely assume that no one will be able to use the form without javascript enabled). It also performs a honeypot captcha check on data in a hidden input field added in the form. The email is then sent:
<?php
//invoke wp_load in order to use WordPress wp_mail plugin function instead of mail for better authentification of the sent email
require_once("/path/to/wp-load.php");
//Check to see if the honeypot captcha field was filled in
if(trim($_POST['checking']) !== '') {
$captchaError = true;
$errors .= "\n Error: Captcha field filled in";
} else {
//Check to make sure that the name field is not empty
if(trim($_POST['name']) === '') {
$errors .= "\n Error: Name field empty";
$hasError = true;
} else {
$name = strip_tags($_POST['name']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '') {
$emailError = 'You forgot to enter your email address.';
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$errors .= "\n Error: Message field empty";
$hasError = true;
} else {
$email = strip_tags($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) === '') {
$errors .= "\n Error: Message field empty";
$hasError = true;
} else {
$phone = strip_tags($_POST['phone']);
$url = strip_tags($_POST['url']);
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = strip_tags($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
// Send Message
$emailTo = 'me#mydomain.com';
$subject = 'Contact Form Submission from '.$name;
$body = "Name: $name \n\nEmail: $email \n\nPhone: $phone \n\nWebsite: $url \n\nMessage: $message";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
wp_mail($emailTo, $subject, $body, $headers);
$alert = 'Thanks! Your request has been sent. One will try to get back to you as soon as possible.';
} else {
$alert = $errors;
}
} ?>
The server keeps track of whether errors were found or whether the email was successfully sent in variable $alert.
After the pHp function completes, the script hides the form from the contact page and displays a previously hidden html element to which it appends an alert message.
The issue I can't solve is making javascript change the wording of that alert message to reflect whether the email was or not successfully sent, because I don't know how to pass the requisite pHp variable ($alert) containing a list of the error messages in the server PHP process to the script for insertion in the Contact Form page. Of course, again, this is a very theoretical concern, since for the reasons stated above, it's unlikely that an error-prone message would even have reached the PHP stage in the first place.
I've tried inserting the following code at the end of the PHP file, to no avail:
<script type="text/javascript">
alert = <?php echo $alert; ?>;
</script>
The latter attempt doesn't generate any errors in Firebug, but the variable value doesn't get passed on. Any ideas or thoughts welcome.
UPDATE: I added this workflow chart to clarify the setup for this issue:
In send-message.php, put the alert text in an IDd <div />:
<div id="statusmsg" style="display: none">
<?php echo $alert ?>
</div>
Then your Javascript on the calling page ought to look like this:
<script type="text/javascript">
$(function() {
$('#contact').validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
url: 'send-message.php',
success: function(data) {
$('#contact').hide();
$('#instructions').hide();
$('#status').show();
$('#popular-posts').show();
// Make DOM object from result
var $DOMObj = $(data);
// Retrieve status message, if any
var $status = $('#statusmsg', $DOMObj);
// Show status message, if any
if ($status) {
$status
.css('display', '')
.appendTo('#status');
}
}
});
}
});
});
</script>
Hopefully you can see how I've used a parameter to the success callback to retrieve the HTML contents of the AJAX request response, located the statusmsg div and appended it to the relevant element on the calling page.
More optimally, send-message.php would print JSON rather than HTML, making this process a little easier. I'll leave that as an exercise for the reader.. at least in this question thread.
You want to return the success or failure of the email in response to the AJAX call.
For this sample example, you could simply return false or true. If you needed more information, return a JSON string such as...
{
"success": true,
"something": ["something", "something-else"]
}
You can easily turn an array into JSON in PHP with json_encode().
var text = $("input#text").val();
if (text == "") {
$("input#text").focus();
alert("Please complete all fields");
return false;
}
I have this jquery above to validate a textarea called "text". This, along with other values, get .ajax sent to a php page for sending an email. The email comes through fine with everything else in ok, but the textarea comes through as "undefined"? Any ideas? Do i need to post some more code?
EDIT:
Rest of the code:
the php:
$email = $_REQUEST['email'] ;
$text = $_REQUEST['text'] ;
$name = $_REQUEST['name'] ;
$detail = "Name: ".$name."\nMessage: ".$text;
mail( "xxxxxxxxx", "Subject: Contact Form",
$detail, "From: $email" );
echo "Thank you for getting in touch";
complete jquery:
$(function() {
$('#submit').live('click',function(){
var name = $("input#name").val();
if (name == "") {
$("input#name").focus();
alert("Please complete all fields");
return false;
}
var email = $("input#email").val();
if (email == "") {
$("input#email").focus();
alert("Please complete all fields");
return false;
}
var text = $("input#text").val();
if (text == "") {
$("input#text").focus();
alert("Please complete all fields");
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&text=' + text;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailform.php",
data: dataString,
success: function() {
alert("Thanks, we will be in touch soon");
}
});
return false;
});
});
The html:
<form method='post' action='mailform.php' class="form">
<p class="name">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</p>
<p class="email">
<label for="email">E-mail</label>
<input type="text" name="email" id="email" />
</p>
<p class="text">
<label for="text">Nature of Enquiry</label>
<textarea id="text" name="text"></textarea>
</p>
<p class="submit">
<input type="submit" id="submit" value="Send" />
</p>
</form>
I had a similar problem and my problem was with the php code. Try yo have a look there see if the #textarea gets _POST - ed correctly.
I am using this and works perfectly for me:
//we need to get our variables first
$email_to = 'xxxxx#yahoo.com'; //the address to which the email will be sent
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message']. "\n\n";
/*the $header variable is for the additional headers in the mail function,
we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
That way when we want to reply the email gmail(or yahoo or hotmail...) will know
who are we replying to. */
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
if(mail($email_to, $subject, $message, $headers)){
echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
}else{
echo 'failed';// ... or this one to tell it that it wasn't sent
}
Not sure what's going on, like the other user said I believe to be a problem with the way the data is being carried over to the php script.
Try to look into $.post and serialize() functions that jquery can offer:
to give you an idea:
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
--- Due some checks to see if the info is correct---
if(error == false){
//#contact_form has all the variables that get serialized and sent to the php
and you can get a message back to check if everything went okay.
$.post("your_php_code.php", $("#contact_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'sent'){
//if the mail is sent remove the submit paragraph
$('#cf_submit_p').remove();
//and show the mail success div with fadeIn
$('#mail_success').fadeIn(500);
}else{
//show the mail failed div
$('#mail_fail').fadeIn(500);
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});