I am trying to create a email form that does not redirect to another other page. I am a newbie at PHP and Javascript .. so basically i have coded like this -
I have included the following code in the mail.php file
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent=" From: $name \n Phone: $phone \n Message: $message";
$recipient = "devtest#xxx.org";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='test.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";
?>
I have uploaded all the files to web server but the problem is that when I am sending test emails, I am not getting blank emails.
The email only contains name of the sender and the email id.
Please let me know where I am messing things up.
<div class="contact">
<div class="contact-wrap">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function verify() {
if (document.getElementById("name").value == "" || document.getElementById("email").value == "") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
//document.getElementById('ContactForm').submit();
var name = $('#name').val();
var email = $('#email').val();
var formData = "name=" + name + "&email=" + email;
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
success: function (data, textStatus, jqXHR) {
//data - response from server
alert(data);
},
});
}
}
</script>
<div class="quick-contact">
<form action="#" id="ContactForm" method="post" action="mail.php">
<p>Your Name (required) <br>
<input type="text" class="form-bt" value="" size="40" name="name" id="name" required>
</p>
<p>Your Email (required) <br>
<input type="email" class="form-bt" value="" size="40" name="email" id="email" required>
</p>
<p>Subject <br>
<input type="text" class="form-bt" value="" name="phone" size="40">
</p>
<p>Your Message<br>
<textarea cols="40" rows="10" class="text-area" name="message" required></textarea>
</p>
<p>
<input type="submit" id="send" onClick="verify()" value="Send" class="btton" onmouseover="this.style.backgroundColor = 'black'" ; onmouseout="this.style.backgroundColor = '#74b9e4'" ;>
</p>
</form>
</div>
</div>
</div>
kind regards
deb
You have just sent email and name. Replace
var formData = "name="+name+"&email="+email;
to
var formData = "name="+name+"&email="+email+"&message="+message;
Also get message variable as :
var message=$('#message').val();
And change the textarea to :
<textarea cols="40" rows="10" class="text-area" name="message" id="message" required></textarea>
You are posting form data with name and email only.
var formData = "name="+name+"&email="+email;
Add fields as necessary.
Also a good way to do this is:
var formData = {
name : $('#name').val(),
email : $('#email').val(),
message : $('#message').val() //Say ID for your message is "message"
}
rather than:
var formData = "name="+name+"&email="+email+"&message="+message;
Related
I have setup the following code to make a contact form that doesn't refresh the page when submitted.
HTML:
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="form-action">
</form>
JavaScript/AJAX request:
$("#contact-form").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = "<?php echo get_template_directory_uri(); ?>/library/contact-form.php";
var posting = $.post( url, {
name: $('#name').val(),
email: $('#email').val(),
subject: $('#subject').val(),
message: $('#message').val(),
});
posting.done(function( data ) {
alert('success');
});
});
PHP:
// Set $to as the email you want to send the test to.
$to = "my#email.com";
// Email subject and body text.
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$headers .= "Reply-To: ". strip_tags($_POST['email']) . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = $_POST["message"];
// send test message using wp_mail function.
if(isset(($_POST['name']), ($_POST['email']), ($_POST['message']), ($_POST["subject"]))) {
$sent_message = wp_mail( $to, $subject, $message, $headers );
} else {
};
//display message based on the result.
if ( $sent_message ) {
// The message was sent.
echo 'The test message was sent. Check your email inbox.';
} else {
// The message was not sent.
echo 'The message was not sent!';
}
The code works when I run it on my local website, It returns the success alert.
The PHP code also succeeds in sending the contact form information to my email address.
I get a 'the server responded with a status of 500 (internal error)' when I run it on my web server.
I think I must have overlooked something stupid here but I can't see it and hoping someone else can see it and help me out?
Thanks in advance!
This is how i do my ajax submission for a form. It's contains WordPress security measures, you can learn them from google in detail but small description will be provided by me.
HTML
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="contact_form" id="cf_action" url="<?= admin_url('admin-ajax.php'); ?>">
<?php wp_nonce_field( 'contact_form', 'contact_form_wpnonce' ); ?>
</form>
Javascript
jQuery(function($){
$("#contact-form").submit(function(e){
var url = $('#cf_action').attr('url');
$.ajax({
type: "POST",
url: url,
data: $("#contact-form").serialize(),
success: function(data) {
alert(data.data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
Function
add_action('wp_ajax_contact_form', 'contact_form_function');
add_action('wp_ajax_nopriv_contact_form', 'contact_form_function');
function contact_form_function()
{
if ( !isset($_POST['xyz_contact_email_meta_box_nonce']) && !wp_verify_nonce($_POST['xyz_contact_email_meta_box_nonce'], 'xyz_save_contact_email_data')) {
# code...
return;
}
$user_name = sanitize_text_field( $_POST['name'] );
$user_email = sanitize_email( $_POST['email'] );
$user_subject = sanitize_text_field( $_POST['subject'] );
$user_message = sanitize_textarea_field( $_POST['message'] );
$to = 'xyz#gmail.com';
$subject = $user_subject;
$body = 'Hi you recived a message from '.$user_name.'('.$user_email.'),<p>'.$user_message.'</p>';
$headers = array('Content-Type: text/html; charset=UTF-8');
$status = wp_mail( $to, $subject, $body, $headers );
if($status){
wp_send_json_success('sent successful');
}else{
wp_send_json_error('something went wrong');
}
}
Description
okay let me guide through WordPress a bit.
WordPress have already inbuilt functionality to handle ajax-request from it's theme's functions.php, you have to copy and paste html code where you want form to show, js code in footer and function code in functions.php
Here are some tips:-
wp_nonce_field = it's used for security purpose and prevent hackers to use form for different purpose.
Sanitize data to make sure you are not receiving any malicious code from your posted data, you can use esc_attr(it will convert any tags and script into html) too.
It's a good habit to send data back with WordPress default function wp_send_json_success & wp_send_json_error.
(Forgive me if you feel hard to understand since it's my first answer on stackoverflow)
Cheers!!
I have a form which a user fills in, the data is sent to my email, but I also wanted email to be posted to my mail chimp using api but it's not working at the moment.
Here is my form:
<form method="POST" onsubmit="return false;" id="dealerForm ">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="subject" name="subject" value="Dealer partner message" type="hidden">
<input class="form-control" placeholder="Your Name *" id="name" name="name" required="" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Email *" id="email" name="email" required="" type="email">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Phone *" id="phone" name="phone" required="" type="tel">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Dearlership Info *" id="message" name="message" required=""></textarea>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-right">
<button type="submit" class="btn send_msg">Send Message</button>
</div>
</div>
</form>
Here is my php with mail chimp api and mail send.
<?php
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'myapikey'; // enter your MailChimp API Key
// ****
$mailchimp_list_id = 'mylistID'; // enter your MailChimp List ID
// ****
$subscriber_email = addslashes(trim($_POST['email']));
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Not a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$merge_vars = array();
require_once 'mailchimp/php/MailChimp.php';
$MailChimp = new \Drewm\MailChimp($mailchimp_api_key);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $mailchimp_list_id,
'email' => array('email' => $subscriber_email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => true,
));
if($result == false) {
$array['valid'] = 0;
$array['message'] = 'An error occurred! Please try again later.';
}
else {
$array['valid'] = 1;
$array['message'] = 'Success! Please check your mail.';
}
echo json_encode($array);
}
}
if (isset($_POST["email#mail.com"])) {
$to = 'mail#mail.com';
$subject = $_POST['subject'];
$message = 'Name: '.$_POST["name"].'<br>Email: '.$_POST["email"].'<br>Phone: '.$_POST["phone"].'<br>Message: '.$_POST["message"];
$headers = 'From: ' . $_POST["email"] . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .
'Content-type: text/html; charset=iso-8859-1;';
if(mail($to, $subject, $message, $headers)){
echo "New record created successfully";
}
}
?>
While my JQuery code:
$("#dealerForm").on("submit", function(){
//debugger;
$.ajax({
type: 'POST',
var url;
url: "contact/dealer.php",
data: $("#dealerForm").serialize()
}).done(function (data) {
//debugger;
console.log(data);
window.location.href = "https://example.com/Thank%20You.html";
});
$("#dealerForm")[0].reset();
return false;
});
Thanks for your comment and your help.
Before mail-chimp fix I think you need to fix followings:
You don't need to use onsubmit="return false;" in form declaration. You already returned false in jQuery onsubmit. And also remove space from form ID name. So, your form declaration can be like <form method="POST" id="dealerForm">
Remove var url; from ajax
Now debug email/mailchimp code in dealer.php.
Many apologies if the answer to my question is obvious.
I am trying to incorporate the Google reCaptcha into my website.
This is the javascript in the HEAD of my page:
var onSubmit = function(token) {
$.ajax({
type: 'POST',
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
The reCaptcha is visible and working.
The above code gives me the result of 'success:' BUT is not processing the form using the call to the php file.
All other scripts on the page are working fine.
Here is the contact.php code:
I've made those changes to my code. No change in the result however. Here is the code for the php file:
<?php
//contact form submission code
//Validate data on the form
// define variables and set to empty values
$name = $email = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = contact_input($_POST["name"]);
$email = contact_input($_POST["email"]);
$message = contact_input($_POST["message"]);
}
function contact_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// if the url field is empty
if(isset($_POST['url']) && $_POST['url'] == ''){
// put your email address here
$youremail = 'my#email.co.uk';
// prepare a "pretty" version of the message
// Important: if you added any form fields to the HTML, you will need to add them here also
$body = "Contact Form from Wilderness Canoe website just submitted:
Name: $_POST[name]
E-Mail: $_POST[email]
Message: $_POST[message]";
// Use the submitters email if they supplied one
// (and it isn't trying to hack your form).
// Otherwise send from your email address.
if( $_POST['email'] && !preg_match( "/.+#.+\..+/i", $_POST['email']) ) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}
// finally, send the message
mail($youremail, 'Contact Form', $body, $headers );
}
?>
and the code for the form:
<form id="form" method="post" action="assets/php/contact.php" onsubmit="return validate();">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-account mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="name"> Full Name</label>
<input class="mdl-textfield__input " type="text" id="name" required name="name">
<!--error msg ><span class="mdl-textfield__error">Only alphabet and no spaces, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-email mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="email">Your Email</label>
<input class="mdl-textfield__input " type="text" id="email" required name="email">
<!--error msg ><span class="mdl-textfield__error">Valid email only, please!</span-->
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<i class="zmdi zmdi-comment-text mdc-text-light-blue zmdi-hc-2x txtfields"></i>
<label class="mdl-textfield__label" for="message">Your Message/Comment</label>
<textarea class="mdl-textfield__input " type="text" rows= "1" max-rows="4" id="message" name="message"></textarea>
</div>
<!-- antispam --><p class="antispam">Leave this empty: <input type="text" name="url" /></p>
<!-- RECAPTCHA -->
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<div class="clear"><button type="submit" value="Send" name="submit" id="mc-embedded-contact" class="send">Submit</button></div>
</form>
The complete javascript:
<script type="text/javascript">
var onSubmit = function(token) {
var formData = $("#form").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
var onloadCallback = function() {
grecaptcha.render('mc-embedded-contact', {
'sitekey' : '6Ldbfg8UAAAAAAaWVBiyo4uGfDqtfcnu33SpOj6P',
'callback' : onSubmit
});
};
</script>
Your ajax request doesnt send any form data in your code. You should add your form data like this:
var onSubmit = function(token) {
var formData = $("#yourFormId").serialize();
$.ajax({
type: 'POST',
data: formData,
url: 'assets/php/contact.php',
success: function(){
alert('Thank you for your request ' + document.getElementById('name').value);
}
});
};
I am trying to create a basic form to send an email and here is how it looks:
http://www.unitedserbians.com/contact_us.html
I have everything working and buttoned up, except I cannot get the actual email to be sent once the form has completed processing. My function executes as my field validations work great and I can see the correct values are being grabbed from the form by un-commenting the JAVA script code "alert (dataString);return false;" and even the .ajax executes because I get "Contact Form Sent! We will be in touch soon." message displayed but the actual email never gets sent. I am guessing that something is missing in the process.php file. I cannot trace to see where the issue occurs or if my process.php ever executes. Should the file live in the same directory with JAVA script? or at main directory bin folder? Or is there something I am blindly missing in the process code? Can someone spot what am I missing please? Much appreciated in advance.
HTML:
<div class="content">
<div class="content_resize">
<div class="mainbar">
<div class="article">
<h2><span>Send us E-Mail</span></h2>
<div id="contact_form">
<form action="" form name="contact">
<fieldset>
<ol>
<li>
<label for="name" id="name_label">Your Full Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label2 class="error" for="name" id="name_error">This field is required.</label2>
</li>
<li>
<label for="email" id="email_label">Your Email Address</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label2 class="error" for="email" id="email_error">This field is required.</label2>
</li>
<li>
<label for="website id="phone_label">Your Phone Number</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label2 class="error" for="phone" id="phone_error">This field is required.</label2>
</li>
<li>
<label for="message">Your Message</label>
<textarea id="message" name="message" rows="8" cols="50"></textarea>
</li>
<li>
<input type="submit" name="imageField" id="submit_btn" src="images/submit.gif" class="send" />
</li>
</ol>
</fieldset>
</form>
</div>
</div>
</div>
JAVA script:
$(function() {
$('.error').hide();
$(".send").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label2#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label2#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label2#phone_error").show();
$("input#phone").focus();
return false;
}
var message = $("textarea#message").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
// alert (dataString);
// return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='send_message'></div>");
$('#send_message').html("<h2>Contact Form Sent!</h2>")
.append("<p>We will be in touch soon.</p>");
}
});
return false;
});
});
PHP:
<?php
$email_to = "XXXXX#gmail.com";
$email_subject = "Message sent using contact form.";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$message = $_POST['message'];
$email_message .= "Full Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Phone Number: ".clean_string($phone)."\n";
$email_message .= "Message: ".clean_string($message)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
One possibility is that your host doesn't like the $email_from address. I think most hosts are restrictive about sending using a From address that isn't associated with that host (this is so to not enable spammers). Try using no-reply#yourdomain.com or something like that, or even better an address that really exists, as your From address. The Reply-To can still be the address the user enters (after you check that it is valid).
Can someone show me how to validate that an email address comes from a certain domain/subdomain like example.com or email.example.com. If it does not come from any of these domains/subdomains then form cannot be submitted.
Here is my form html:
<form name="form" method="post" action="mail.php">
<input name="email" type="email" id="email" placeholder="email#gmail.com" required>
<input name="name" type="text" id="name" placeholder="name" required>
<button type="submit" id="submit">Submit!</button>
</form>
Please show me how to integrate it into my form above
Thanks
This is what i tried so far:
<form name="form" method="post" action="mail.php">
<input name="email" type="email" id="email" placeholder="email#gmail.com" required>
<input name="name" type="text" id="name" placeholder="name" required>
<button type="submit" id="submit">Submit!</button>
</form>
<script>
function IsValidEmail(email)
$(document).ready(function() {
$("#form").submit(function() {
var allowedDomains = [ 'x.com', 'y.com', 'z.com' ];
if ($.inArray(str[0], allowedDomains) !== -1) {
//acceptable
}else{
//not acceptable
}
</script>
mail.php file
<?php
$to = $_POST["email"];
$name = $_POST["name"];
$subject = "Test mail";
$message = "Hello! This is a simple email message.\n
Name: $name\n
Email: $to\n
Sending IP: $_SERVER[REMOTE_ADDR]";
$from = "test#example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
i tried this script found at Allow only specific email address' domain to register through JQuery (preferably)
However, you forgot the most relevant part: Getting the part after the # sign and testing that against the array. The str[0] you're currently using is still undefined.
$("#form").submit(function() {
var allowedDomains = [ 'x.com', 'y.com', 'z.com' ];
var domain = $("#email").val().split("#")[1];
if ($.inArray(domain, allowedDomains) !== -1) {
//acceptable, do nothing
} else{
//not acceptable, prevent submit event
}
});
Also notice that you forgot some closing braces…