So I've got this AJAX contact form, the code of which I've used before. I can't work out quite why it isn't working.
HTML
<div id="website-contact-form">
<form id="website_contact" name="website_contact">
<input id="email-address-input" name="website-email" type="text" placeholder="Your email here" class="order-form-input" /><br />
<textarea name="website-message" placeholder="Please give a brief description of what you have in mind, plus contact details." class="order-form-textarea"></textarea>
</form>
</div>
JS
<script type="text/javascript">
$(document).ready(function(){
$('#submit-website-project').click(function (e) {
e.preventDefault();
if ($('#email-address-input').val() != ""){
postForm("ajax/contact-website.php", "website_contact",
function (data) {
if (data == "success") {
$('#website-contact-form').
html("<br />Thankyou for your enquiry. I'll "+
"get in touch shortly.");
} else {
alert("That didn't work. Try again?");
}
});
}
});
}); //END DOCUMENT READY
function postForm(url, form_id, success_func) {
$.ajax({
type: "POST",
url: url,
data: $("#" + form_id).serialize(),
success: function (data) {
success_func(data);
}
});
}
</script>
And finally my PHP
<?php
if (isset($_POST['email'])) {
$_POST['email'] = trim(#$_POST['email']);
$ToEmail = 'barneywimbush:gmail.com';
$EmailSubject = 'Barneywimbush.com';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Email: ".$_POST["email"]."";
$MESSAGE_BODY .= "Comment: ".nl2br($_POST["project_description"])."";
$res = mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader); // or die ("Failure")
if ($res) {
echo "success";
}
else {
echo "failed";
}
}
else {
echo "failed";
}
I'm just getting the alert "That didn't work. Try again?"
Your PHP variables for your $_POSTs are incorrect, on checking the Network panel, your form is sending off,
website-email: yes#test.com
website-message: Test data
Whilst your PHP code is looking $_POST['email'], were it should be $_POST['website-email'];
Change the name attribute of your input elements to change the param name for the request.
Related
I want to display svg image and text after submitting the contact form but i don't have any experience in php, So can you guys help out in this problem. Right now after submitting the form it's simply display "Your message has been sent successfully" after clicking the submit button.
See the attached image which i want to display Image link
<form id="contact-form" action="formProcess.php">
<ul class="contact-inputs">
<li><input type="text" name="your_name" id="name" placeholder="Name"></li>
<li><input type="email" name="email" id="email" placeholder="Email"></li>
<li><input type="text" name="subject" id="subject" placeholder="Subject"></li>
<li><textarea name="message" id="message" cols="30" rows="5" placeholder="Message"></textarea></li>
<li class="send-btn"><button type="submit" id="submit">Send</button></li>
</ul>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "formProcess.php",
dataType: "json",
data: {name:name, email:email, subject:subject, message:message},
success : function(data){
if (data.code == "200"){
//alert("Success: " +data.msg);
$(".display-error").html(data.msg);
$(".display-error").css("display","block");
$("#contact-form").css("display","none");
} else {
$(".display-error").html("<ul>"+data.msg+"</ul>");
$(".display-error").css("display","block");
}
}
});
});
});
</script>
<?php
$errorMSG = "";
/* NAME */
if (empty($_POST["name"])) {
$errorMSG = "<li>Name is required</li>";
} else {
$name = $_POST["name"];
}
/* EMAIL */
if (empty($_POST["email"])) {
$errorMSG .= "<li>Email is required</li>";
} else if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$errorMSG .= "<li>Invalid email format</li>";
}else {
$email = $_POST["email"];
}
/* SUBJECT */
if (empty($_POST["subject"])) {
$errorMSG .= "<li>Subject is required</li>";
} else {
$subject = $_POST["subject"];
}
/* MESSAGE */
if (empty($_POST["message"])) {
$errorMSG .= "<li>Message is required</li>";
} else {
$message = $_POST["message"];
}
if(empty($errorMSG)) {
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "umerzamanlive#gmail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Subject: $subject\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
(mail($recipient, $subject, $email_content, $email_headers));
$success .= "Your message has been sent successfully";
echo json_encode(['code'=>200, 'msg'=>$success]);
exit;
}
echo json_encode(['code'=>404, 'msg'=>$errorMSG]);
I found a tutorial for a simple contact form using fancyBox. I was able to apply the form into my website, and then modify the code of the form to meet my needs. But my form is not working.
Once I put in all of the information into the form and I press the Send Email button, the button then disappears and I get a "sending..." which is what it supposed to do if all of the fields are "true". But it does not want to do the last step which is to run the php file.
The form also came with the php file necessary for this to work, but it doesn't send it.
Does the php file have to be in an specific place in the website? I have tried to place it from several different locations but to no avail.
<div id="inline">
<form id="contact" name="contact" action="#" method="post">
<label for="name">Your Name </label>
<input type="text" id="name" name="name" class="txt">
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
<script type="text/javascript">
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var nameval = $("#name").val();
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
var namelen = nameval.length;
if(namelen < 2) {
$("#name").addClass("error");
}
else if(namelen >= 2) {
$("#name").removeClass("error");
}
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4 && namelen >= 2) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! We will respond to your request as soon as possible.</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
sendmessage.php
<?php
$sendto = "antiques47#aol.com";
$username = $_POST['name'];
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "More information request";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$username."</p>\r\n";
$msg .= "<p><strong>Email:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>
I tried changing the ACTION on the form to the specific file, but it didn't work either.
I noticed that the ajax part also has the URL to send message.php, I tried to change that so it has a specific directory to the file but that did not work.
Updated:
You are changing the From: attribute in your mail headers. Some ISPs will block outgoing emails that do that. This could be your problem. Comment out the line:
$headers = "From: " . strip_tags($usermail) . "\r\n";
and try again.
If that fails, check each step of the AJAX:
.1. In sendmessage.php, change the very top of the file to read:
<?php
die('Got to here');
.2. Then, back in your ajax code block, amend it (temporarily) to read:
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
alert(data);
}
});
This will at least tell you if it is communicating.
.3. Then, echo back the POST items that you received, to ensure there isn't a problem there:
PHP:
$username = $_POST['name'];
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$out = 'username [' .$username. ']';
$out .= 'usermail [' .$usermail. ']';
$out .= 'content [' .$content. ']';
echo $out;
Again, see what is echo'd out by the ajax success function.
I have this problem with my contact form. When I submit the form I receive 2 identical emails in my box.
Im using JS to check the form for errors and then simple PHP mail() function to send the email.
Here is the PHP code:
<?php
$from = Trim(stripslashes($_POST['email']));
$to = "myemail#gmail.com";
$subject = "Contact Form";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$number = Trim(stripslashes($_POST['number']));
$message = Trim(stripslashes($_POST['message']));
$body = "";
$body .= "Name: ";
$body .= $name;
$body .= "\n\n";
$body .= "E-mail: ";
$body .= $email;
$body .= "\n\n";
$body .= "Telephone Number: ";
$body .= $number;
$body .= "\n\n";
$body .= "Message: ";
$body .= $message;
$body .= "\n\n";
$success = mail($to, $subject, $body, "From: <$from>" . "\r\n" . "Reply-to: <$from>" . "\r\n" . "Content-type: text; charset=utf-8");
?>
And here is the JS:
$(".submit").click(function() {
var name = $("input[name=name]").val();
var email = $("input[name=email]").val();
var number = $("input[name=number]").val();
var message = $("textarea[name=message]").val();
if (defaults['name'] == name || name == "") {
$(".error").text("Please enter your name!");
return false;
} else if (defaults['email'] == email || email == "") {
$(".error").text("Please enter your email!");
return false;
} else if (defaults['number'] == number || number == "") {
$(".error").text("Please enter your number!");
return false;
} else if (defaults['message'] == message || message == "") {
$(".error").text("Plese enter your message!");
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&number=' + number + '&message=' + message;
$(".error").text("Please wait...").hide().fadeIn("fast");
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function() {
$('#form form').html("");
$('#form form').append("<div id='success'>Your message has been sent! Thank you</div>");
}
});
return false;
});
And here is the HTML form:
<form id="contact" method="post" action="#">
<label for="name">Name:</label>
<input type="text" name="name" required tabindex="1">
<label for="email">Email adress:</label>
<input type="text" name="email" required tabindex="2">
<label for="number">Tel. number:</label>
<input type="text" name="number" tabindex="3">
<label for="message">Your message:</label>
<textarea name="message" rows="10" cols="70" required tabindex="4"></textarea>
<input type="checkbox" id="terms" name="terms" value="terms">I agree to the terms
<input type="submit" name="submit" class="submit more-info" tabindex="5" value="Send">
<span class="error"></span>
</form>
I have been using the same code for all of my contact forms and it worked all right. Could it be hosting/server related issue?
replace your click event
$(".submit").click(function() {
with
$('.submit').unbind('click').click(function() {
code.
What I can assume your click event is binding two times may be due to a lot of the mess in the code
also use this line in the end of the click event function
$('.submit').unbind('click').click(function() {
// your stuff
event.stopImmediatePropagation(); // as long as not bubbling up the DOM is ok?
});
for reference have a look at the link: https://forum.jquery.com/topic/jquery-executes-twice-after-ajax
$(".submit").click(function(e) { ... }) POSTS to your server for the first time.
Because this is a <submit> button, the form will still submit. The form POSTS to your server for the second time.
The solution would be adding a e.preventDefault() at the bottom inside the $(".submit").click function...
$(".submit").click(function(e) {
// ^ add this e
var name = ...;
$.ajax({
...
});
e.preventDefault();
return false;
});
Try removing the jQuery animations:
$(".error").text("Please wait...").hide().fadeIn("fast");
They can sometimes cause problems.
i have a contact form and it sends just with php atm, i want to send it with ajax?
whats the easiest way?
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!$hasError) {
$emailTo = '123#gmail.com'; // Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
if(wp_mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
}else{
echo '<p class="alert-message error">Error sending mail.</p>';
}
}
}
?>
Please maybe give pointers on also improving the send function.
Any help really appreciated.
if you need to see the form let me know and i will edit and put it in
You can modify your code as follows.
Below is a stand-alone example (untested) of exactly what you requested.
Simply copy/paste the two code blocks into two files:
contacttest.php (or whatever you wish to call it)
yourphpprocessor.php (if change name, must also change it in AJAX code block)
Note that:
1. Each form element now has an ID attr
2. <form> functionality is no longer used at all, and is in fact prevented via e.preventDefault()
HTML: contacttest.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
$(document).ready(function() {
//If you want the output from php side in a lightbox...
$('#alertmsg').dialog({
autoOpen: false,
modal: true,
width: 400,
buttons: {
Thanks: function() {
$(this).dialog('close');
}
}
});
$('#contactform').submit(function(e) {
e.preventDefault();
var frm = $('#cname').val();
var eml = $('#cemail').val();
var sub = $('#subj').val();
var msg = $('#msg').val();
//validation goes here, for eg.
if (frm == '' || eml==''){
alert('All fields must be completed');
return false;
}
$.ajax({
type: "POST",
url: "yourphpprocessor.php",
data: 'f=' +frm+ '&e=' +eml+ '&s=' +sub+ '&m=' +msg,
success: function(recd) {
$('#alertmsg').html(recd);
$('#alertmsg').dialog('open'); //Uses lightbox to display message
}
});
}); //END AJAX
}); //END $(document).ready()
</script>
</head>
<body>
<form id="contactform" action="" method="POST">
From: <input type="text" name="contactname" id="cname"><br />
Email: <input type="text" name="email" id="cemail"><br />
Subject: <input type="text" name="subject" id="subj"><br />
Message: <textarea name="message" id="msg"></textarea><br /><br />
<input type="submit" id="mysubmit" value="Submit">
</form>
<div id="alertmsg"></div>
</body>
</html>
PHP Side: yourphpprocessor.php
<?php
$name = $_POST['f'];
$email = $_POST['e'];
$subject = $_POST['s'];
$comments = $_POST['m'];
$emailTo = '123#gmail.com'; // Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
if(wp_mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
}else{
echo '<p class="alert-message error">Error sending mail.</p>';
}
?>
You need to do this on the client side
Just use this plugin http://jquery.malsup.com/form/
The form on my website is a simple contact form.
I would like the form to show a "success & failed" message on the same page when the form is sent/failed without reloading the page. I understand that I should use Ajax to do this but I can't get it to work because my knowledge about it is very little.
Here is the code I'm working with.
Html (single page design):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<form class="form" id="contactus" action="" method="post" accept-charset="UTF-8">
<label for="nametag">Namn<FONT COLOR="#FF0060">*</FONT></label>
<input name="name" type="text" id="name" value="" />
<label for="emailtag">Email<FONT COLOR="#FF0060">*</FONT></label>
<input name="email" type="text" id="email" value="" />
<label for="phonetag">Telefon</label>
<input name="phone" type="text" id="phone" value="" />
<label for="messagetag">Meddelande<FONT COLOR="#FF0060">*</FONT></label></br>
<textarea name="message" id="message" style="width: 87%; height: 200px;"></textarea>
<label class="placeholder"> </label>
<button class="submit" name="submit">Skicka</button>
</form>
<script>
$(function() {
$('#contactus').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'php/mail.php',
data: $('#contactus').serialize(),
success: function(res) {alert(res);
if (res == 'successful') {
$('#status').html('Sent').slideDown();
}
else {
$('#status').html('Failed').slideDown();
}
},
error: function () {
$('#status').html('Failed').slideDown();
}
});
});
});
</script>
Php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$recipient = "info#mydomain.com";
$subject = "Webbkontakt";
$formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";
$headers = "From: " ."CAMAXON<info#mydomain.com>" . "\r\n";
$headers .= "Reply-To: ". "no-reply#mydomain.com" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=utf-8\r\n";
if(mail($recipient, $subject, $formcontent, $headers))
{
echo "successful";
}
else
{
echo "error";
}
?>
Your Ajax call is not working properly. Try this
$(function() {
$('#contactus').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'php/mail.php',
data: $('#contactus').serialize(),
success: function(res) {
if (res == 'successful') {
$('#status').html('Sent').slideDown();
}
else {
$('#status').html('Failed').slideDown();
}
},
error: function () {
$('#status').html('Failed').slideDown();
}
});
});
});
Also as you can see i have used $('#contactus').serialize() this way you dont need to pass the form elements one by one instead serialize() will pass the whole form elements to your php page
Than in your php file echo successful if everything went well else echo error if the response is an error than show the error div
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$recipient = "info#mydomain.com";
$subject = "Webbkontakt";
$formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";
$headers = "From: " ."CAMAXON<info#mydomain.com>" . "\r\n";
$headers .= "Reply-To: ". "no-reply#mydomain.com" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if(mail($recipient, $subject, $formcontent, $headers))
{
echo "successful";
}
else
{
echo "error";
}
?>
Change your PHP script like this:
<?php
if( isset( $_POST['submit'] )){ //checking if form was submitted
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent="Meddelande: \n\n $message";
$recipient = "info#mydomain.com";
$subject = "Webbkontakt";
$mailheader = "Från: $name \n Email: $email \n Telefon: $phone \r\n";
$mailsent = mail($recipient, $subject, $formcontent, $mailheader);
if($mailsent) echo "Success"; //success if mail was sent
else echo "Ett fel uppstod!";
}
?>
Below your mail() function, simply do echo "successful";
2020 Edit
In REST API response should be always accompanied by the correct HTTP status code, with 200+ telling client that request ended up correctly processed or was otherwise good, 400+ telling client there was an error in request, and 500+ that there was a problem with the server itself. Do not use statuses inside responses, it is unnecessary duplication of the existing feature:
http_response_code(200);
echo json_encode(['message' => 'Email was sent']);
exit;
Then you can handle request and response with jQuery(assuming that you still use jQuery):
$.ajax({
url: url,
data: data,
dataType: 'json'
})
.then(function (data, textStatus, jqXHR) {
// Your 200+ responses will land here
})
.fail(function (jqXHR, textStatus, errorThrown) {
// Your 400+ responses will be caught by this handler
});
;
If you need specific status, you can get it from jqXHR parameter using jqXHR.status field.
Original answer
You can use dataType: 'json' in your ajax call.
Then you'll be able to pass status code as response key:
// form response array, consider it was success
$response = array( 'success'=> 'ok', 'message' => 'Email was sent');
echo json_encode($response);
In js then you can check data.success === 'ok' to know what's your status.
In your php script you could try this
if(mail($recipient, $subject, $formcontent, $mailheaders))
{
echo("Mail Sent Successfully"); // or echo(successful) in your case
}else{
echo("Mail Not Sent"); // or die("Ett fel uppstod!");
}