I'm making a simple contact form, I have an old school php mailer mail.php and a jQuery front page from where I'm calling it.
As I wanted it to work, it should've stayed on same page, but it actually jumps to mail.php and displays the message
Thank you for contacting me. I'll try to reach you ASAP.
Though it does send the mail, thats still not acceptable as that was not my intention. Can anybody find out what I'm doing wrong here ?
Any help appreciated.
PHP:
<?php
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
$emailTo = 'myEmail#gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $message";
$headers = 'From: Saddi website <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
echo "Thank you for contacting me. I'll try to reach you ASAP.";
return true;
?>
FORM (Lot of bootstrap tags there, so to keep it clean I'm just posting ):
<form class="form" action="mail.php" method="post" id="contact-form">
</form>
And here goes my AJAX:
var data_string = jQuery('#contact-form').serialize();
jQuery.ajax({
type: "POST",
url: "mail.php",
data: {name:name,email:email,message:message},
timeout: 6000,
error: function(request,error) {
if (error == "timeout") {
jQuery('#timedout').fadeIn('slow');
setTimeout(function() {
jQuery('#timedout').fadeOut('slow');
}, 3000);
}
else {
jQuery('#state').fadeIn('slow');
jQuery("#state").html('The following error occured: ' + error + '');
setTimeout(function() {
jQuery('#state').fadeOut('slow');
}, 3000);
}
},
success: function() {
jQuery('span.valid').remove();
jQuery('#thanks').fadeIn('slow');
jQuery('input').val('');
jQuery('textarea').val('');
setTimeout(function() {
jQuery('#thanks').fadeOut('slow');
}, 3000);
}
First i will recommend you to use jQuery Form Plugin, very helpful for this kind of ajax post and validations.
jQuery Form
Second, you can use event.preventDefault(); to avoid the default action of the link but it will really depend on how are you triggering your form to the ajax code
event.preventDefault
Related
I have a problem with reloading the page. After clicking submit form the page reloads. I click send the form and takes me to http: // localhost: 3000 / mail.php. And I would like the site not to be reloaded. (I use the validation form jquery plugin).This is my code:
jquery
(function(){
$("#contactForm").on('submit', function(e) {
e.preventDefault();
var data = {
name = $('#field-name').val(),
phone = $('#field-phone').val(),
email = $('#field-email').val(),
message = $('#field-message').val()
};
$.ajax({
type: "POST",
url: "mail.php",
data: data,
success: function(){
console.log("jej");
}
});
return false;
});
});
and php code
<?php
$to = 'name#gmail.com';
$name = $_POST['name'];
$phone = $_POST['phone'];
$email= $_POST['email'];
$text = $_POST['message'];
$subject = 'Nowy e-mail od ' . $name . ' (' . $email . ')';
$message = $name . $phone . $email . $text;
$headers = 'From: ' . $name . "\r\n" .
if(mail($to, $subject, $message, $headers)) {
print "<p class='success'>Mail Sent.</p>";
} else {
print "<p class='Error'>Problem in Sending Mail.</p>";
}
?>
change part of your code
$("#contactForm").on('submit', function(e)
to this...
$("#contactFormButton").on('click', function(e)
and change your submit button to this...
<button id="contactFormButton" type="button" class="form-control">Submit</button>
and here your php code...
if(mail($to, $subject, $message, $headers)) {
echo "Mail Sent!";
} else {
echo "Error!!";
}
and here you can catch result of your php code...
success: function(data){
console.log(data);
}
First question and first time looking at PHP so please bear with me.
I currently have the below jQuery which is calling a php file:
$(document).on('click', '#btnContactUs', function () {
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("input#message").val();
var dataString = 'name='+ name + '&email=' + email + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "php/message.php",
data: dataString,
success: function(response) { alert(response); }
});
return false;
});
The console is logging the call as successful (XHR finished loading: POST "php/message.php").
Below is the full script in the file:
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
The email is not being sent/received (I am checking Spam also).
The files are hosted on a web server which has PHP installed. The alert box is popping up, but empty. The initial AJAX call is made from a submit button on a webpage.
EDIT: I am sending this to my personal email, which I have not included above.
EDIT: Even when visiting the URL of the script the email is still not being sent.
FINAL EDIT: The resolution is that my server did not have PHP mail installed - it is not supported as it is considered unreliable and therefore they recommend SMTP. To figure this out I used DrewT's solution of using SSH to check for "which sendmail"
Hope this scenario helps someone in the future.
Thanks all.
What seems to be happening is you are not sending your information in the correct format because you don't parse your var dataString on the server. I would try something like:
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("input#message").val();
Then in your post function:
$.ajax({
type: "POST",
url: "php/message.php",
data : { name: name, email: email, subject: subject, message: message },
success: function (response, status, err) {
// do stuff...
// NOTE: don't return false or it won't send
// 'return false' only if the form is incomplete
// and you don't want the email sent out prematurely
}
});
Then to receive these vars in your PHP:
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
Now you can send an email like this:
// Enter your send email address
$to = 'email#example.com';
// Add your headers
$header = "from: $name <$email>";
// only send it if we have all the data we need
if( $subject !== "" || " " && $message !== "" || " " && $name !== "" || " " && $mail_from !== "" || " " ) {
$send_contact = mail($to,$subject,$message,$header);
// check if message was sent
// and provide some formatting (html) to send along in our response
if ($send_contact) {
echo '<div class="msg-sent">
Your message was sent successfully yay!
</div>';
}
else {
echo '<div class="msg-send-failed">
SEND FAILED :0
</div>';
}
}
else {
echo '<div class="msg-had-empty">
YOU HAD EMPTY POST VARIABLES :0
</div>';
}
Beyond that you will need to debug using the networks tab in your browser's inspector./ good luck!
I need to send email asynchronously.
For that I have a jQuery ajax client and PHP backend to actually send eMail, still AJAX's success method is not being called. I understand it is simple, but yet doesn't seem to be working. Can somebody please take a look at my code and see what I'm doing wrong? Really appreciate it.
$.ajax({
type: "POST",
url: "mail.php",
data: {name: "manu", email: "abc#abc.com"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('mail sent');
$('#divToBeWorkedOn').html(msg);
}
});
and I have mail.php
<?php
header("Content-type: application/json");
$name = trim($_POST['name']);
echo $name
$email = trim($_POST['email']);
$msg="my email";
$emailTo = 'myemail#gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $message";
$headers = 'From: Saddi website <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
echo 1;
?>
I see 2 problems.
you're echoing just 1, its not JSON. So in your PHP code do json_encode("msg"=>"1");
In my experience, if you have this
header("Content-type: application/json");
OR header("Content-type: json/text");
You won't get any result in jquery success or error blocks.
success: function(msg) {
alert(msg);
}
the msg would return null value (or nothing). The alert will happen but will show something like object object.
It's the HTML contact form:
<form class="form" method="post" action="mail.php">
<label for="name">Name:</label>
<input class="name" type="text" name="name" value="" placeholder="Full Name" required>
<label for="email">Email:</label>
<input class="email" type="text" name="email" value="" placeholder="Email" required>
<label for="message">Message:</label>
<textarea class="message" rows="4" cols="20" name="message" placeholder="Type..." required></textarea>
<input type="submit" value="Send">
It's the Ajax I use for my contact form:
$('.form').submit(function() {
var name = $(".name").val();
var email = $(".email").val();
var message = $(".message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function() {
$(".form").hide();
$(".notice").fadeIn(400);
}
});
return false;
});
And it's my mail.php (I found here):
<?php
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example#example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
} else {
header("Location: your_form.html");
}
I just want to add an "Invalid Email Address" message to my form with Ajax (in order to show besides the form, Not in another page)
In the current form when the user submit a filled and valid inputs, it shows a Success message (.notice), but nothing happen when you submit the form with an invalid email address.
You can try passing arrays from your PHP script back to your AJAX response as data, and let your script handle whatever that is passed back :) In my example below, I have chosen to pass the PHP response back to your AJAX script using the json_encode function, and arbitrarily selected a type of status code that will be read by your JS function to take appropriate action :)
Also, in order your $.ajax to read JSON data correctly, you should include the line dataType: "json" in the function.
Overall, the suggested changes will be:
Echo a response from your PHP script in JSON format using json_encode()
Allows your PHP script to pass the response to your JS script
Ensure that your AJAX function reads the JSON format, and then take the appropriate action
For example, in your PHP script, you can use:
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
// If email is valid
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example#example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
if(mail($recipient, $subject, $formcontent, $mailheader)) {
// If mail is sent
// Status is arbitrary. You can use a string, number... I usually use numbers
$resp = array("status"=>1, "message"=>"Mail successfully sent.");
} else {
// If sending failed
$resp = array("status"=>2, "message"=>"Error with sending mail.");
}
} else {
// If email failed filter check
$resp = array("status"=>3, "message"=>"You have provided an invalid email address. Please check the email address provided.");
}
// Echos the $resp array in JSON format, which will be parsed by your JS function
echo json_encode($resp);
In your JS file, you can parse the JSON response:
$('.form').submit(function() {
// Define variables to construct dataString. You don't need to use var to declare each variable individually ;)
var name = $(".name").val(),
email = $(".email").val(),
message = $(".message").val();
// Construct dataString
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
// Ajax magic
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data) {
if(data.status == "1") {
$(".form").hide();
$(".notice").fadeIn(400);
} else if (data.status == "2") {
// Error handling for failure in mail sending
} else if (data.status == "3") {
// Error handling for failure in email matching
} else{
// Catch all other errors
}
}
});
return false;
});
First change your PHP to output Invalid Email Address in case for invalid email address, then check if that message exists as response from ajax:
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example#example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
}else{
echo "Invalid Email Address";
}
And change ajax to:
$('.form').submit(function() {
var name = $(".name").val();
var email = $(".email").val();
var message = $(".message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function(data) {
if(data.indexOf("Invalid Email Address") >= 0){
alert("Invalid Email Address");
}else{
$(".form").hide();
$(".notice").fadeIn(400);
}
}
});
return false;
});
You're going to want to use regular expressions for this, and filter_var. We'll be validating in both Javascript and PHP because the user might not have Javascript enabled.
The regular expressions I normally use to validate emails is this:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
When your forms gets submitted you'll want to run something like this:
var email = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
if(email.test($('.email').val()) === FALSE) {
$('.notice').html('<strong>Invalid email address!</strong>').show();
return false;
}
In your PHP once you've checked if the POST request is valid and has all the fields you need you'll want to run filter_var with the FILTER_VALIDATE_EMAIL parameter. filter_var returns a boolean.
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
echo 'Invalid email address!';
exit;
}
I have a site running on Windows Azure that contains a simple contact form for people to get in touch. Unfortunately, that form isn't work right now...
I have an index.php file that contains the form:
<div class="form">name="name" placeholder="Name" id="contactname" />
<input type="text" name="email" placeholder="Email" id="contactemail" />
<textarea name="message" placeholder="Message" id="contactmessage"></textarea>
<button>Contact</button>
</div>
I then have a JS file like this:
if ($('#contact').is(":visible")) {
$("#contact button").click(function() {
var name = $("#contactname").val();
var message = $("#contactmessage").val();
var email = $("#contactemail").val();
var emailReg = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$/;
// client-side validation
if(emailReg.test(email) == false) {
var emailValidation = false;
$('#contactemail').addClass("error");
}
else
$('#contactemail').removeClass("error");
if(name.length < 1) {
var nameValidation = false;
$('#contactname').addClass("error");
}
else
$('#contactname').removeClass("error");
if(message.length < 1) {
var messageValidation = false;
$('#contactmessage').addClass("error");
}
else
$('#contactmessage').removeClass("error");
if ((nameValidation == false) || (emailValidation == false) || (messageValidation == false))
return false;
$.ajax({
type: "post",
dataType: "json",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html('<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>');
}
});
return false;
});
};
and finally, a php file to send the email called send-email.php:
$destination = 'info#clouddock.co'; // change this to your email.
// ##################################################
// DON'T EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING
// ##################################################
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$subject = $name;
$headers = "From: ".$name." <".$email.">\r\n" .
"Reply-To: ".$name." <".$email.">\r\n" .
"X-Mailer: PHP/" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
mail($destination, $subject, $message, $headers);
}
When I fill in the contact form, the JS validation appears to be working, and when I click send the 'Thanks for getting in touch...' text appears, as if the message has been sent. But I don't receive any email. Can anyone advise as to where the problem might be? Could it be Azures configuration blocking the messages from being sent out?
You are using $("#contact").serialize() to get data to send but you've got no elements with ID contact.
You should use $("#contactname, #contactemail, #contactmessage").serialize() (and fix first input ;) ).
And always validate input data in PHP, not only in JS!
Of course it will display the thanks message, all it needs is a response back from the server. What you need is to test whether the mail actually sent or not, then return that back to your original script to determine what message to show.
if(mail($destination, $subject, $message, $headers)) {
return '<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>';
} else {
return '<p class="fail">The e-mail failed to send.</p>';
}
And then set your AJAX to:
$.ajax({
type: "post",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html(data);
}
});
You'll probably find that you get the fail message, and that could well be the setup of your server, or it could be you not passing the right thing to the mail() function. You then need to debug your script to find out whether the right information is being passed etc.
With Windows servers they need to be configured to pass all mail from the mail() function to an SMTP server, so if that's not been done on your Azure server then your mail will instantly fail.