I am trying to set up my page so that when I a form is submitted it emails and a message is displayed without refreshing the page.
I have tried to do this using jQuery/Ajax however I cannot get any emails sent now
Without the Ajax/jQuery, the PHP works just fine but just doesnt include the refresh feature
Any help would be appreciated
PHP (submitForm.php):
<?php
$name = isset($_POST['name']);
$email = isset($_POST['email']);
$phone = isset($_POST['phone']);
$message = isset($_POST['message']);
$feedback = '';
if($name && $email && $phone && $message) {
$name = ($_POST['name']);
$email = ($_POST['email']);
$phone = ($_POST['phone']);
$message = ($_POST['message']);
}
$to = "arshdsoni#gmail.com";
$subject = 'Soni Repairs - Support Request';
$body = <<<EMAIL
Hi There!
My name is $name.
Message: $message.
My email is: $email
Phone Number: $phone
Kind Regards
EMAIL;
$header = "From: $email";
if($_POST) {
if($name == '' || $email == '' || $phone == '' || $message == '') {
$feedback = "Nothing received!";
}
else {
mail($to, $subject, $body, $header);
$feedback = '*Message Received! You will receive a reply shortly!';
}
}
?>
jQuery/Ajax:
function submitForm() {
var name=document.getElementById('name').value;
var dataString = 'name'+ name;
$.ajax({
type:"post",
url:"submitForm.php",
cache:false,
success: function(html) {
$('#feedback').html(html);
}
});
return false;
}
FORM:
<form id="contact" action="#">
<h3>Get in Touch:</h3>
<h4><span id="star" class="glyphicon glyphicon-asterisk"></span>We aim to reply within 24 hours!</h4>
<fieldset>
<input name="name" placeholder="Your Name" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<input name="email" placeholder="Your Email Address" type="email" tabindex="2" required>
</fieldset>
<fieldset>
<input name="phone" placeholder="Your Phone Number" type="tel" tabindex="3" required>
</fieldset>
<fieldset>
<textarea id="textarea" name="message" placeholder="Describe your problem...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit submitBtn" data-submit="...Sending" "return submitForm();">Submit</button>
</fieldset>
</form>
Issues:
if you usedocument.getElementById you must use id on your elements
Add the data to your ajax request
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$( "#submitBtn" ).click(function( event ) {
alert('pressed');
//values
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var dataString = {"name": name, "email":email, "phone": phone, "message":message}
$.ajax({
type:"post",
url:"submitForm.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
event.preventDefault();
});
});
</script>
</head>
<body>
<form id="contact" method="POST">
<h3>Get in Touch:</h3>
<h4><span id="star" class="glyphicon glyphicon-asterisk"></span>We aim to reply within 24 hours!</h4>
<fieldset>
<input id="name" placeholder="Your Name" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<input id="email" placeholder="Your Email Address" type="email" tabindex="2" required>
</fieldset>
<fieldset>
<input id="phone" placeholder="Your Phone Number" type="tel" tabindex="3" required>
</fieldset>
<fieldset>
<textarea id="message" placeholder="Describe your problem...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<button name="submit" id="submitBtn">Submit</button>
</fieldset>
</form>
<div id="feedback"></div>
</body>
</html>
PHP
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['phone'], $_POST['message'])){
//Post data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
//mail settings
$to = "arshdsoni#gmail.com";
$subject = 'Soni Repairs - Support Request';
$body = <<<EMAIL
Hi There!
My name is $name.
Message: $message.
My email is: $email
Phone Number: $phone
Kind Regards
EMAIL;
if(mail($to, $subject, $body, $header)){
$feedback = '*Message sent! You will receive a reply shortly!';
}else{
$feedback = '*Message failed to send';
}
}else{
$feedback = 'Missing Params';
}
echo $feedback;
This is your ajax, where you went wrong
$.ajax({
type:"post",
url:"submitForm.php",
cache:false,
success: function(html) {
$('#feedback').html(html);
}
});
You forgot to include the data to be posted
$.ajax({
type:"post",
url:"submitForm.php",
cache:false,
data {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
message: $('#msg').val()
}
success: function(html) {
$('#feedback').html(html);
}
});
The keys name, email, message and phone should be as is; because you used $_POST['name'], $_POST['email'], $_POST['message'] and $_POST['phone'].
The calls$('#name').val(), $('#email').val(), $('#phone').val(), $('#message').val() have been made assuming that your input elements have ids name, email, message and phone respectively. JS uses ids rather than names.
Refer to jQuery Ajax documentation for more details.
I do not see you sending the data to PHP file anywhere in your AJAX code
NOTE: Use serialize() function if you want to send all the form data. Else send it separately like
var formDatas = {name:"name",email:"emailID"};
function submitForm() {
var name=document.getElementById('name').value;
var dataString = 'name'+ name;
var formDatas = $('#formID').serialize(); // Send form data
$.ajax({
type:"post",
url:"submitForm.php",
data : {datas : formDatas }
cache:false,
success: function(html) {
$('#feedback').html(html);
}
});
return false;
}
Your references
jQuery Serialize()
jQuery ajax()
Related
Sounds like an odd question but here is what I have. The php has a snippet at the end that says success or failure makes a white screen to display this, I really want it to pop up right under the submit button on the same page rather than redirect the entire page.
I assume I could direct that to an empty <div>?
mail.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent=" From: $name \n Phone: $phone \n Message: $message";
$recipient = "art#jamisonsigns.com";
$subject = "Web Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";
?>
With a simple HTML form on my website as follows:
<form class="contact-form" form action="mail.php" method="POST">
<fieldset>
<input type="text" class="name" id="name" placeholder="Name...">
</fieldset>
<fieldset>
<input type="email" class="email" id="email" placeholder="Email...">
</fieldset>
<fieldset>
<input type="text" class="phone" id="phone" placeholder="Phone...">
</fieldset>
<fieldset>
<textarea name="message" id="message" cols="30" rows="4" placeholder="Message.."></textarea>
</fieldset>
<fieldset>
<input type="submit" class="button" id="button" value="Send Message">
</fieldset>
</form>
You need to submit the form with Ajax. Then on success insert the message in the html.
$('#button').click(function(event) {
event.preventDefault();
var formdata = $('#formID').serializeArray();
var url = '/urltopost.php';
$.ajax(
{
url : url,
type: "POST",
data: formdata,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
console.log("STATUS:" + textStatus + " | jqXHR:" + jqXHR + " | data:" + data);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR:" + " -> " +errorThrown);
}
});
});
Here it is a tutorial if you need..
So this must look as another PHP email question. However, after researching and trying all available replies on Stackoverflow, I can't seem to get the <textarea name="description"></textarea> to get the content and send it with the rest of the email $to, $from, $body and $headers:
Here's the HTML:
<form method="post" id="tarqus_form">
<div class="inner-frame inverse p-7">
<h5>Hola,</h5>
<div>
<h5>mi nombre es</h5>
<input type="text" class="name" name="name" placeholder="Nombre (obligatorio)" id="name">
</div>
<div>
<h5>y me gustaría saber</h5>
</div>
<div>
<h5>sobre:</h5>
<input type="text" class="subject" name="subject" placeholder="Asunto" id="asunto">
</div>
<div>
<h5>Me pueden responder</h5>
</div>
<div>
<h5>a este:</h5>
<input type="text" class="email" name="email" placeholder="Correo electrónico (obligatorio)" id="email">
</div>
<div>
<h5>Quisiera decir:</h5>
</div>
<div>
<!-- HERE's the textarea -->
<textarea name="description" rows="3" class="message" placeholder="Ingresa tu mensaje (obligatorio)" id="message"></textarea>
</div>
<div class="row pt-21">
<div class="col-md-6 p-0">
<h5>Antispam:</h5>
<div>
<h5>¿12-7+2?</h5>
</div>
<div>
<input type="text" class="antispam pl-0 mt-7 ml-0" name="antispam" placeholder="Respuesta (obligatorio)" id="antispam">
</div>
</div>
<div class="col-md-6 text-center">
<input type="submit" value="Enviar" class="submit uppercase">
</div>
</div>
</div>
</form>
I'm creating some validations with jQuery and if they pass, the POST method is called. This hasn't been a problem because the email is actually being sent with everything I need except the message on the textarea.
jQuery validations:
$("#tarqus_form").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var subject = $("#asunto").val();
var email = $("#email").val();
var text = $("#message").val();
var antispam = $("#antispam").val();
var dataString = 'email=' + email + '&text=' + text + '&subject=' + subject + '&name=' + name;
// Custom RegExp for verifying email authenticity
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) && (name.length > 1) && (text.length > 1) && (antispam == 7)){
$.ajax({
type: "POST",
url: "/form.php",
data: dataString,
success: function(response){
console.log(response);
$('#tarqus_form').fadeOut(500);
$('.success').removeClass('hidden').fadeIn(500);
}
});
} else{
$('.error').removeClass('hidden').fadeIn(1000);
setTimeout(function(){
$('.error').addClass('hidden');
}, 5000);
}
return false;
});
When this passes, the form sends the email according to this PHP code:
<?php
$name = $_POST['name'];
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['description'];
$from = 'TARQUS | Arquitectura MX <contacto#tarqus.mx>';
$headers.="From:".$from."\n";
$to = 'contacto#tarqus.mx';
$body = "Nombre: $name\n Asunto: $subject\n E-Mail: $email\n Mensaje: $message\n";
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
#mail($to, $subject, $body, $headers);
?>
As you can see, I'm using the $_POST method for my name="description" textarea. I've also tried with the $_REQUEST method.
Here's an example email, all of the changes that I've made to the PHP code sent the email except for the $message in the $body:
Nombre: Name Lastname
Asunto: Subject
E-Mail: example#mail.com
Mensaje: === empty === :(
you got error on your php file
when you getting post DATA in ajax you sending TEXT not DESCRIPTION
$name = $_POST['name'];
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['text'];
$from = 'TARQUS | Arquitectura MX <contacto#tarqus.mx>';
$headers.="From:".$from."\n";
I am working on a website with an Ajax contact form. Tried a lot, it successfully sends a mail without headers below is my code please help me to fix this
code
<div class="form">
<div class="title">
<h2 class="orange"><span class="orange">Contact</span> US</h2>
</div>
<div class="height15"></div>
<div id="return_message"></div>
<div class="field">
<label>First Name:</label>
<input name="name" type="text" />
</div>
<div class="field">
<label>Phone Number:</label>
<input name="phone" type="text" />
</div>
<div class="field">
<label>Email Address:</label>
<input name="email" type="text" />
</div>
<label>Message:</label>
<textarea name="message" cols="" rows=""></textarea>
<div class="clear"></div>
<a class="org_btn more submit" id="submit" href="#.">Submit</a> </div>
<script language="javascript">
$(document).ready(function() {
$("#menu_btn").click(function(){
$("#sub_menu").slideToggle("slow");
});
//Contact us form validation
$('#return_message').hide();
$('#submit').click(function(event){
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
var message = $('#message').val();
if( (name=='') || (phone=='') || (email=='') || (message=='') )
{
$('#name').addClass('error_active');
$('#phone').addClass('error_active');
$('#email').addClass('error_active');
$('#message').addClass('error_active');
}
else
{
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email))
{
alert("Please Enter valid email address");
$('#email').addClass('error_active');
}
else
{
$.ajax(
{
type: 'POST',
data: ({name : name, phone : phone, email : email, message : message}),
url: 'send_mail.php',
success: function(data)
{
if(data)
{
$('#return_message').show('slow').html("<p>Email has been sent...</p>");
$('#name').val('');
$('#phone').val('');
$('#email').val('');
$('#message').val('');
$('#name').removeClass('error_active');
$('#phone').removeClass('error_active');
$('#email').removeClass('error_active');
$('#message').removeClass('error_active');
}
else
{
$('#return_message').show('slow').html("<p>Email has not been sent...</p>");
}
}
});
}
}
});
});
</script>
php code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$to = "info#kodspider.com"; // Please put your email addres.
$subject = "Marthoman Vidyapeedom"; //Please put subject of your email.
if($phone!='')
{
$message2 = $message.'\r\nPhone:'.$phone;
}
else
{
$message2 = $message;
}
$message = $message.'\r\nPhone:'.$phone;
$headers = "From: ".$email;
$sent = mail( $to, $subject, $message2, $headers );
if($sent)
{
echo "success";
}
else
{
echo "error";
}
?>
you have given
<input name="name" type="text" />
but in jquery your calling
$('#name').val('')
in jquery # selector is used only for id
make change
<input name="name" id="name" type="text" />
for more details in jquery read this
Heys guys, I've been playing around with this ajax call for a few days now. I had it posting an email with no variables earlier, but now I can't get the call to submit the form with a variable or without. Here is my code:
<form id="contactform" method="post" action="submit.php">
<input type="text" placeholder="Name" name="username" id="username" />
<input type="email" placeholder="Your Email Address" name="email" id="email" />
<input type="button" id="submit" class="submit" value="submit"></a>
</form>
AJAX:
<script type="text/javascript">
$("#submit").click(function(event){
var data = $('#contactform').serialize();
event.preventDefault();
$.ajax({
url: "submit.php",
type: "POST",
data: data,
success: function() {
alert("Success!");
}
});
return false;
});
});
</script>
submit.php:
<?php
$from = "info#email.com";
$usersubject = "Thank You!";
$usermessage = "Thank you for signing up!";
$to = $_REQUEST['email'];
$subject = "Form Info";
?>
<?php
$name = $_REQUEST['username'];
$email = $_REQUEST['email'];
$message = "Name: $name
Email: $email";
$headers = "From:" . $from;
//mail($to,$subject,$message,$headers);
mail($email,$usersubject,$usermessage,$headers);
echo 'Success';
?>
submit.php works when you access it directly with the variable (www.website.com/submit.php?username=Dave&email=davesemail#mail.com). Is there an error somewhere here that I'm missing? Any help is appreciated!
This what you want but you should learn about Json.
data={
"name":"James Bond","email":"AGENT007#MI5.gov "
}
If you don't use a document ready block:
$( document ).ready(function() {
// your code here
});
Then make sure you put your javascript code just before the closing body tag ().
Otherwise if you put the javascript in the header without a document ready the javascript code will be executed before the submit button is present on the page and therefor the $('#submit') selector will return zero elements.
HTML:
<form method="post" action="submit.php">
<input type="text" placeholder="Name" name="username" id="username" />
<input type="email" placeholder="Your Email Address" name="email" id="email" />
<input type="button" onClick="submit()" value="submit"></a>
</form>
AJAX:
<script type="text/javascript">
function submit(){
var user = document.getElementById("username").value;
var email = document.getElementById("email").value;
$.ajax({
url: "submit.php",
type: "POST",
data: {uname:user,email:email},
success: function() {
alert("Success!");
}
});
return false;
}
</script>
PHP:
<?php
$from = "info#email.com";
$usersubject = "Thank You!";
$usermessage = "Thank you for signing up!";
$to = $_POST['email'];//one that assigned to data in ajax
$subject = "Form Info";
?>
<?php
$name = $_POST['uname']; //one that assigned to data in ajax
$email = $_POST['email'];//one that assigned to data in ajax
$message = "Name: $name
Email: $email";
$headers = "From:" . $from;
//mail($to,$subject,$message,$headers);
mail($email,$usersubject,$usermessage,$headers);
echo 'Success';
?>
Okay so I have a form that is using PHP to mail to an e-mail address. I also have a jQuery/AJAX section that validates the form without reloading the page and executes the PHP. For some reason the Product Interest value from the interest drop down is not coming through in the e-mail. What am I missing? I've been driving myself mad with this. Thanks!
This is the form:
<div class="contact-form">
<div class="row">
<div class="field"><input type="text" id="first" name="first" class="input" placeholder="First Name"></div>
<div class="field"><input type="text" id="last" name="last" class="input" placeholder="Last Name"></div>
<div class="field"><input type="text" id="telephone" name="telephone" class="input" placeholder="Phone Number"></div>
</div>
<div class="row">
<div class="field"><input type="email" id="email" name="email" class="input" placeholder="E-mail"></div>
<div class="field">
<select class="select" name="interest" id="interest">
<optgroup label="Countwise Products:">
<option value="I-Count">I-Count</option>
<option value="Q-Count">Q-Count</option>
<option value="D-Count">D-Count</option>
<option value="Z-Count">Z-Count</option>
</optgroup>
</select>
</div>
<input type="submit" value="Get Better Results!" class="button3 dark-blue submit"/>
<span class="error" style="display:none">All Fields Are Required!</span>
<span class="success" style="display:none">Contact Form Submitted Successfully</span>
</div>
</div>
</form>
This is the PHP for titled header_form_email.php
<?php
// POST Variables
//Name
$first = $_POST['first'];
$last = $_POST['last'];
//Phone
$telephone = $_POST['telephone'];
//E-mail
$email = $_POST['email'];
//Interest
$interest= $_POST['interest'];
// Contact subject
$subject = "CountWise Website - Sales Request";
$name = "$first" . " " . "$last";
$message = "You have received a new information request from Countwise.com\n".
"Name: " . "$name\n".
"Phone: " . "$telephone\n".
"Email: " . "$email\n".
"Product Interest: " . "$interest";
// From
$mailheader = "From: $email \r\n";
// Enter your email address
$to ="kelly#drastikdesigns.com";
$send_contact=mail($to,$subject,$message,$mailheader);
// Check, if message sent to your email
if($send_contact){
echo "<strong>We have received your information and will be in contact you shortly. Thank you.</strong>" ;
}
else {
echo "ERROR";
}
?>
This is the AJAX
$(function() {
$(".submit").click(function() {
var first = $("#first").val();
var last = $("#last").val();
var telephone = $("#telephone").val();
var email = $("#email").val();
var interest = $("#interest").val();
var dataString = 'first=' + first + '&last=' + last + '&telephone=' + telephone + '&email=' + email + '&interest' + interest;
if (first == '' || last == '' || telephone == '' || email == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else {
$.ajax({
type: "POST",
url: "http://www.drastikdesigns.com/clients/countwise/php/header_form_email.php",
data: dataString,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
You forgot the equals:
'&interest=' + interest;
On a side note, why not just do:
data:$("#formid").serialize(),
That will save you tons of time and headache. Second point, using firebug/developers tools/chrome definitely helps when it comes to viewing the headers sent via ajax.