Sending e-mail form using PHP and AJAX - javascript

I have contact form on my site. It sends message to email. I try to do it without page reload using AJAX, but it seems that AJAX doesn't work: messages are sent but the page still redirecting to call-form.php. What is incorrect in my code? (jQuery is included)
HTML
<form name="freeCall" action="<?php bloginfo(template_url); ?>/mail/call-form.php" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
</form>
PHP - call-form.php
<?
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
}
?>
JS
$(function () {
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
});

Ok, first when you make an AJAX call, you must have a way to know if your PHP returns you something (useful for debugging).
Then, when submitting a form with AJAX, the tag action="" is not needed.
Finally, to prevent a form from being sent when making an AJAX call, add e.preventDefault() with the event called e here, like in my example.
I have improved your code to be more realistic about the latest standards.
HTML :
<form name="freeCall" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
JS :
$(function () {
$("#free-call-form").submit(function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
dataType: "json", // Add datatype
data: form_data
}).done(function (data) {
console.log(data);
alert("It's OK!");
}).fail(function (data) {
console.log(data);
});
});
});
And PHP :
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
echo json_encode(array('status' => 'success'));
} else {
echo json_encode(array('status' => 'error'));
}
With echo json_encode, you know what is the return of your AJAX call. It is better

You're not preventing the default submit action -
$("#free-call-form").submit(function (event) { // capture the event
event.preventDefault(); // prevent the event's default action

Returning false or preventing the default behavior of the event should work for you.
Example with old .submit(), that now is an alias of .on('eventName'); and using return false to avoid form submission.;
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
return false;
});
Example using .on('eventName') and using e.preventDefault() to avoid form submission.
$("#free-call-form").on('submit', function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
From Jquery .submit() Documentation: This method is a shortcut for
.on( "submit", handler ) in the first variation, > and .trigger(
"submit" ) in the third.
Also, you would consider not using EVER the user input directly, it would not cause problems in this exact context (or maybe yes) but with your actual approach they can change the mail markup or adding some weirds things there, even scripts, you would consider escape, validate or limit it.
Also as zLen pointed out in the comments:
the action in the form markup is not necessary because you are not using it, you can remove it:
action="<?php bloginfo(template_url); ?>/mail/call-form.php"

What is happening is your form is being submitted, it's not actually the AJAX call which is doing it. To fix it, add
return false;
at the end of the submit function so that the browser doesn't submit the form and the AJAX call happens properly.

Related

Google invisible recaptcha using jquery and php

I'm trying to add Google's invisible recaptcha in my website. It is basically for a contact us form where the user submits his name, email and message and on clicking submit will trigger a mail to us.
I planned to take care of the mail part using php. However, I am not able to get past submitting the form in jquery.
This is my html :
<div class="row">
<script src="mail.js"></script>
<form id="main-contact-form" name="contact-form">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Name" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="form-group">
<textarea name="message" class="form-control" rows="2" placeholder="Message" required></textarea>
</div>
<button class="g-recaptcha btn btn-primary" data-sitekey="6LdGAiQUAAAAAHeNXI3yDSsZhLAJs7U1HX_zXm8o" data-callback="onSubmit" type="submit">Submit</button>
</form>
</div>
The onSubmit callback:
function onSubmit(response) {
var request;
console.log('here');
document.getElementById('main-contact-form').submit();
}
The jQuery code for passing the submitted form to the php where verification of the captcha is done mail is sent:
$("#main-contact-form").submit(function(event) {
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
console.log('in here');
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function(response, textStatus, jqXHR) {
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function(jqXHR, textStatus, errorThrown) {
// Log the error to the console
console.error(
"The following error occurred: " +
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function() {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
Php code for mailing:
<?php
$name;$email;$message;$captcha;
if(isset($_POST['name'])){
$name=$_POST['name'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['message'])){
$message=$_POST['message'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
exit;
}
$secretKey = "secret key";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha.);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>Message could not be sent</h2>';
} else {
$name = #trim(stripslashes($name));
$from = #trim(stripslashes($email));
$subject = #trim(stripslashes('contact'));
$message = #trim(stripslashes($message));
$to = 'email#email.com';//replace with your email
$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();
mail($to, $subject, $message, $headers);
echo '<h2>Thanks for posting comment.</h2>';
}
?>
?>
The PHP code might not be correct and I am yet to work on that (I haven't used PHP before.).
Now, when I try to submit the form, the page reloads with the form as query params in the address bar. Even, when event.preventDefault() is given for when the form is submitted in the onSubmit callback of Recaptcha, it reloads the page.
Please help me with getting this working. Also I do not want to refresh the page when the form is submitted as I plan to use ajax for sending the form input to the php script.

Sending a file from form to email

I am trying to figure out how to send a file that containts things like images to text files, etx from a form submission through ajax to my php file to send into an email. I am trying to format it the way I have my other data in ajax and php email, but I can tell the form stops right away in my ajax. It doesn't even send through to my php, but I am not sure if I have the email part right either.
This is what I tried so far. I tried to delete as much obsolete code as possible, but still include enough to give a good feeling for what I am trying to do.
How can I make this file attach/send into an email from a form through AJAX to my php email
<form action="" autocomplete="on" method="POST" id="project-information-form" enctype="multipart/form-data">
<input type="text" class="input-borderless" id="project-name" name="name" placeholder="Your Name">
<input type="email" class="input-borderless" id="project-email" name="email" placeholder="Email Address">
<input type="number" class="input-borderless" id="project-number" name="phone" placeholder="Phone Number">
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple>
<label for="file"><span id="file-upload-image"><img src="/icons/white-upload.png" height="25px" width="25px"></span>File Upload</label>
<input type="submit" id="submit-project" class="submit-project-button" value="Send Project Inquiry">
</form>
AJAX
$("#submit-project").on("click", function(event) {
// event.preventDefault();
var project_name = $("#project-name").val();
var project_email = $("#project-email").val();
var project_number = $("#project-number").val();
var uploaded_file = $("#file").val();
submitHandler: function(form) {
console.log(form);
$.ajax({
url: "email-project.php",
type: "POST",
data: {
"project_name": project_name,
"project_email": project_email,
"project_number": project_number,
"file": project_file
},
success: function(data) {
//console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to send email!");
alert(data);
} else {
}
},
PHP Page for email
ini_set('display_errors', 1);
error_reporting(E_ALL);
$project_name = $_POST['project_name'];
$project_email = $_POST['project_email'];
$project_number = $_POST['project_number'];
$project_file = $_POST['file'];
$to = '';
$subject = '';
$message = '
<html>
<head>
<title>Project Inquiry Form Sent</title>
</head>
<body>
<p>There has been a Project submitted. Here are the details:</p><br>
<p>Name: '. $project_name .'</p>
<p>Email: '. $project_email .'</p>
<p>Phone Number: '. $project_number .'</p>
<p>The client uploaded a file ' .$project_file.'.</p>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:' .$project_email . "\r\n";
if (!empty($project_email)) {
if (filter_var($project_email, FILTER_VALIDATE_EMAIL)) {
//Should also do a check on the mail function
if (mail($to, $subject, $message, $headers)) {
echo "Your email was sent!"; // success message
} else {
echo "Mail could not be sent!"; // failed message
}
} else {
//Invalid email
echo "Invalid Email, please provide a valid email address.";
}
} else {
echo "Email Address was not filled out.";
}
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method sends the form data to the server, then a script on the server handles the upload.
Here's an example using PHP. Take a look at this example.
Credit goes here -> jQuery AJAX file upload PHP
$('#submit-project').on('click', function() {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'email-project.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});

Jquery, PHP and Ajax form without refreshing

I try to prepare simple contact form with jquery, ajax and php without refresh. Everything works fine besides event.preventDefault();
That's my files:
contact_engine.php
<?php
$name = $_POST['name'];
...
$from = 'from';
$to = 'to';
$subject = 'subject';
$human = '4';
$body = ".........";
if ($_POST['submit'] && $human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Thanks</p>';
} else {
echo '<p>Error</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
?>
Ajax/jQuery
$('form').on('submit', function(event){
event.preventDefault();
$.ajax('.../contact_engine.php', {
type: 'POST',
data: $('form').serialize(),
success: function(result) {
}
});
});
PHP
<form method="post" action="<?php bloginfo('template_directory'); ?>/contact_engine.php">
<div class="box">
<input type="text" name="name" class="pola formbg name" placeholder="Name" />
.
.
.
.
<p><input id="form-button" type="submit" name="submit" value="Send" /></p>
</div>
<br style="clear: left;" />
</form>
When I remove event.preventDefault(); everything is ok, I receive a message from form but site are refreshing and I see 'thanks' message.
I used Wordpress as you probably seen.
Yeah, in this kind of instance why have a form/submit button.
Remove the form and change the input from a submit button to a standard button.
Put the function on the button, job done.
$('#form-button').on('click', function(event){
$.ajax('.../contact_engine.php', {
type: 'POST',
data: $('form').serialize(),
success: function(result) {
//do something with the return code
}
});
});
Give your form an ID - I think the problem is your submit handler does is not firing:
$( "#myForm" ).submit(function( event ) {...
and then change your jQuery to read:
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
...
See http://api.jquery.com/jquery.post/

Sending data to server with $.ajax request

I have a simple form with 2 input:
<form name="contact" id="contact">
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
On submit I want using jQuery ajax method to send data to print.php. Code looks next:
var contact=$("#contact");
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
I want that Print.php script simply prints sent data, but nothing is happening. Script looks next:
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
echo $fname;
?>
Problem is obviusly in print.php.
you need to use following.
$("form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "print.php",
dataType: "json",
data: {
fname: firstName,
lname: lastName
},
success: functon(dt) {
alert(dt);
}
});
});
There is no $subject variable anywhere.
You set the first name and last name variables properly.
To check your script's response (which will be an error), go to your console and check network, and then repsonse data.
Change $subject to $fname and it should "work"
Also add on .on() submit event handler to your jQuery AJAX call like so:
$('form').on('submit', function() {
//ajax call
});
Edit:
You made an edit and changed $subject to $name. There is no $name variable either.
You do not need the JSON type on the ajax form. And include the preventDefault to avoid natural action(page refreshes when submitting)
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
event.preventDefault();
$.ajax({
type:"POST",
url:"print.php",
data:{
fname:firstName,
lname:lastName
}
});
});
It looks like your problem is that your HTML form doesn't know where to go ounce the submit happens and that is why nothing is happening. You need to tell your HTML form to run javascript.
You could link your HTML form to your javascript by using JQuery's .submit() method document here http://api.jquery.com/submit/
This will trigger your javascript to run once it is submitted if you wrap all your javascript around it.
$("form").submit(function( event ) {
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
Also you could give your HTML form an action so it knows what to do when the form is submitted.
Below we are saying run myFunction() when this form is submitted, we will then need to wrap all your javascript in myFunction().
<form name="contact" action=“javascript:myFunction();”>
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
Your javascript will look like this
function myFunction(){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
}
Once you get that far you will want to fix your php. The way you have it now $name is empty and won't print anything. You will want to fill the variable in before you echo it out. I am assuming you want $name to contain a concatenated version of $fname and $lname.
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
$name = $fname . ' ' . $lname;
echo $name;
?>
That should work for you.

Send jQuery variable by mail

I have a jQuery variable that contains HTML and values from a form. I would like to send it via email using a seperate php file with #mail.
I am trying to send this variable with the jQuery $.ajax function on form submit but it doesn't send the variable to the php file and therefore, no email is sent.
Here is my code
jQuery :
$('form').submit(function(){
var foo = '<p>Some message</p>';
$.ajax({
url: '/send.php',
type: 'post',
data: {foo : foo},
success: function() {
alert('email sent!');
}
});
return false;
});
send.php :
<?php
$email_to = "XXX";
$email_from = "YYY";
$email_message = $_POST["foo"];
$email_subject = "[Email subject]";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
I tried to echo the foo variable in send.php and removing return false; in the jQuery but The variable doesn't seem to pass to the file and nothing is displayed.
What am I doing wrong?
Your code is OK! We are supposing your PHP web server is working, So the 2 only possible error are:
url: '/send.php'
Are you sure send.php is in the root of your domain? Like
http://localhost/send.php
The second possibility is that you a have a previous javascript fatal error, so your ajax lines will never be readed...
How to debug?
1 - Are your pages refreshing when you post your form? If yes, there's an previous error that prevents return false; to be readed
2 - You can press F12 in most of browsers to open developer tools, in this case the Network Panel is what you need: Just try your code with this panel opened and see what happens there... 404 error code means "I cant find send.php!".
This FIDDLE gets a 404 because http://fiddle.jshell.net/send.php doesn't exists.
Try This works for you.
<html>
<body>
<form method="post" class="mailform" onsubmit="return false;">
<input type="submit" value="submit"/>
</form>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).on('submit','form',function()
{
var foo = '<p>Some message</p>';
$.ajax({
url: 'send.php',
type: 'post',
data: {'foo' : foo},
success: function() {
alert('email sent!');
}
});
return false;
});
</script>
</body>
</html>

Categories

Resources