I decided to ask this question because there is no simple answer to it.
I have a contact form in my home.php which looks like:
HTML:
<form id="js-calculator" name="calculator" action="" method="post">
<input type="email" name="email" id="email" placeholder="E-mail" />
<input type="tel" name="phone" id="phone" placeholder="Phone" />
<textarea name="message" id="message" placeholder="Message"></textarea>
<label for="accept"><input class="" type="checkbox" id="accept" name="accept" /> I agree to terms and conditions</label>
<button type="submit" id="send__btn">Wyślij wycenę</button></p>
</form>
JavaScript:
jQuery(document).ready(function ($) {
$('#js-calculator').submit(function (e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: '<?php echo admin_url("admin-ajax.php") ?>',
type: 'post',
dataType: 'JSON',
data: $this.serialize()
}
});
});
});
PHP in functions.php
// Function to send emails
function sendMail () {
$subject = 'Automatic evaluation';
$headers = 'From: My Website Contact Form <contact#mysite.com>';
$send_to = "office#mysite.com, ". $_POST['email'];
$subject = "Evaluation for ". $_POST['name'];
$message = "Message from ".$_POST['message'];
}
add_action('wp_ajax_sendhtmlmail', 'sendMail');
add_action('wp_ajax_nopriv_sendhtmlmail', 'sendMail');
add_filter( 'wp_mail_content_type', 'set_content_type' );
function set_content_type( $content_type ) {
return 'text/html';
}
// Function to update DB
function addCustomer(){
global $wpdb;
$phone = $_POST['phone'];
$email = $_POST['email'];
$accept = $_POST['accept'];
if($wpdb->insert('customers',array(
'phone'=>$phone,
'email'=>$email,
'accept'=>$accept
))===FALSE){
echo "Error";
} else {
$wpdb->insert_id;
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
What I would like to achive is:
1. Send an HTML email to client and to website admin,
2. Add client details to Database, check if email exists,
3. Have a secure connections and data flow;
Right now I have no idea what I`ve done wrong... Any help will be much appreciated.
You are almost there, couple of things:
In your JS ajax call, you need to specify the action to call, here's modified call:
jQuery(document).ready(function ($) {
$('#js-calculator').submit(function (e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: '<?php echo admin_url("admin-ajax.php?action=sendhtmlmail") ?>',
type: 'post',
dataType: 'JSON',
data: $this.serialize()
}
});
});
});
Now, lets look at the php functions:
// Function to send emails
function sendMail () {
$data = array(
'email' = sanitize_email($_POST['email']),
'name' = sanitize_text_field($_POST['name']),
'message' = sanitize_text_field($_POST['message']),
);
$subject = 'Automatic evaluation;
$headers = 'From: My Website Contact Form <contact#mysite.com>';
$send_to = "office#mysite.com, ". $data['email'];
$subject = "Evaluation for ". $data['name'];
$message = "Message from ".$data['message'];
wp_mail($send_to, $subject, $message, $headers);
addCustomer($data);
// TODO: Fill in this $response array with meaninfull data (check output from wp_mail and addCustomer)
$response = array(
'success' => true
);
wp_send_json($response);
}
add_action('wp_ajax_sendhtmlmail', 'sendMail');
add_action('wp_ajax_nopriv_sendhtmlmail', 'sendMail');
Just missing the wp_mail call, and the cleanup of the inputs, I removed your other ajax call, and have the sendMail function just pass the data to the addCustomer function. You'll notice a wp_send_json call, this is to send the response to the JS. https://codex.wordpress.org/Function_Reference/wp_send_json
Now lets look at your addCustomer function:
// Function to update DB
function addCustomer($data){
global $wpdb;
$phone = $data['phone'];
$email = $data['email'];
$accept = $data['accept'];
if($wpdb->insert('customers',array(
'phone'=>$phone,
'email'=>$email,
'accept'=>$accept
))===FALSE){
return false;
} else {
return $wpdb->insert_id;
}
}
The only thing that change here, is the return, so that the caller knows if it failed.
To handle inputs from user, check this doc from wordpress and core functions:
https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data
Or you could use the following plugins together:
https://wordpress.org/plugins/contact-form-7/
https://wordpress.org/plugins/flamingo/
Here's how to use it: https://contactform7.com/save-submitted-messages-with-flamingo/
I hope this helps you!
Regards,
P.S wordpress questions are better suited here: https://wordpress.stackexchange.com/
Related
This is confusing me any ideas as to why I only receive the telephone number (missing the name and email fields) when a form is submitted? Ive tried changing everything but i can't seem to get the other 2 fields to work when submitted.
<aside class="sidebar">
<h3 class="text-center">Request a Callback</h3>
<div class="enquiry-wrapper">
<form id="enquiry-form" method="post" action="enquiry.php" class="clearfix">
<input type="text" name="enquiry-name" id="enquiry-name" autocomplete="off" placeholder="Name ...">
<input type="email" name="enquiry-email" id="enquiry-email" autocomplete="off" placeholder="Email ...">
<input type="tel" name="tel" id="tel" autocomplete="off" placeholder="Phone Number ...">
<div class="form-submit">
<input type="submit" class="btn btn-colour" name="enquiry-submit" id="enquiry-submit" value="Send message">
</div>
<!-- form-submit end -->
</form>
<div id="enquiry-message"></div>
</div>
<!-- enquiry-wrapper end -->
</aside>
This is the enquiry.php
<?php
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$from = 'contact#rpsfm.co.uk';
// an email address that will receive the email with the output of the form
$sendTo = 'contact#rpsfm.co.uk';
// subject of the email
$subject = 'new contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('enquiry-name' => 'Name', 'enquiry-email' => 'Email', 'tel' => 'Tel');
// message that will be displayed when everything is OK :)
$okMessage = header( 'Location: http://rpsfm.co.uk/thanks1.html' );
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
?>
This is the js.
jQuery(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function() {
var e = $(this).attr("action");
$("#enquiry-message").slideUp(750, function() {
$("#enquiry-message").hide();
$("#enquiry-submit").after("").attr("disabled", "disabled");
$.post(e, {
name: $("#enquiry-name").val(),
email: $("#enquiry-email").val(),
tel: $("#tel").val()
}, function(e) {
document.getElementById("enquiry-message").innerHTML = e;
$("#enquiry-message").slideDown("slow");
$("#enquiry-form img.loader").fadeOut("slow", function() {
$(this).remove()
});
$("#enquiry-submit").removeAttr("disabled");
if (e.match("success") != null)
$("#enquiry-form").slideUp("slow")
})
});
return false
})
});
Hope I've done this right if not let me know any more info you need.
ATB
Luke
there are multiple things which make me wonder, besides that I do not understand what you are trying to accomplish.
In enquiry.php:
// message that will be displayed when everything is OK :)
$okMessage = header( 'Location: http://rpsfm.co.uk/thanks1.html' );
Taken this excerp from the manual:
The second special case is the "Location:" header. Not only does it
send this header back to the browser, but it also returns a REDIRECT
(302) status code to the browser unless the 201 or a 3xx status code
has already been set.
By passing this to a variable you are redirecting almost instantly before executing your code.
Secondly your JavaScript code does not seem to work as you desire. I think you want to send your form via AJAX, but your code is ignored, because the form is send via regular post.
event.preventDefault(); should prevent the sending of the form via regular submit.
Used like
jQuery(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function(event) {
event.preventDefault();
// [...]
});
});
I update as I come along with more issues.
Update
Please take a look at this:
$(document).ready(function() {
"use strict";
$("#enquiry-form").submit(function(event) {
event.preventDefault();
var e = $(this).attr("action");
$("#enquiry-message").slideDown(750, function() {
$("#enquiry-message").hide();
$("#enquiry-submit").after("").attr("disabled", "disabled");
$.post(e, {
"enquiry-name": $("#enquiry-name").val(),
"enquiry-email": $("#enquiry-email").val(),
"tel": $("#tel").val()
}, function(e) {
document.getElementById("enquiry-message").innerHTML = e;
$("#enquiry-message").slideDown("slow");
$("#enquiry-form img.loader").fadeOut("slow", function() {
$(this).remove();
});
$("#enquiry-submit").removeAttr("disabled");
if (e.type === "success") {
$("#enquiry-form").slideUp("slow");
}
});
});
});
});
You have used the wrong variable names for the POST data. So your assoc array in the enquiry.php could not use the correct keys and left it out. It seems like the assignment of the header() function works, but it seems like very bad practice to me. You could return the ok message with your AJAX return call, instead of using the header() function.
Small problem here, I need to place a button on my 404 page to ask people to submit an error.
The problem is that nothing is actually happens, I mean no mail is received and no errors are displayed, so I am confused.
My report is very basic, it collects all data of what my user did before getting 404
$site = "mySite.com";
$email = "donotreply#mySite.com";
$http_host = $_SERVER['HTTP_HOST'];
$server_name = $_SERVER['SERVER_NAME'];
$remote_ip = $_SERVER['REMOTE_ADDR'];
$request_uri = $_SERVER['REQUEST_URI'];
$cookie = $_SERVER["HTTP_COOKIE"];
$http_ref = $_SERVER['HTTP_REFERER'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$error_date = date("D M j Y g:i:s a T");
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "404 Error Report for ".$site."\n";
$message .= "Date: ".$error_date."\n";
$message .= "Requested URL: http://".$http_host.$request_uri."\n";
$message .= "Cookie: ".$cookie."\n";
$message .= "Referrer: ".$http_ref."\n";
$message .= "User Agent: ".$user_agent."\n";
$message .= "IP Address: ".$remote_ip."\n";
$message .= "Whois: http://ws.arin.net/cgi-bin/whois.pl?queryinput=".$remote_ip;
this is my form, all fields are hidden that are placed in the same file along with php code above
<form name="form" method="POST" id="report-form">
<div class="form">
<input type="hidden" name="message" value="$message">
<div class="done">
<p><strong>Thank you!</strong></p>
</div>
<div class="error">
<p><strong>Error!</strong> Sorry, something went wrong, please try again.</p>
</div>
<input type="hidden" name="visitor" value="">
<input type="hidden" name="submitted" value="submitted">
<input type="submit" name="submit" value="Submit" class="formSubmit" />
</div>
</form>
<script type="text/javascript" src="js/report_validation.js"><\/script>
here is my jQuery validation script, which I am trying to use, which is in the separate file named report_validation.js in js folder
$(document).ready ( function() {
$('.formSubmit').click(function() {
// Store values in variables
var form = $(this).closest('form');
var message = form.find('input[name=message]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'message=' + message.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "includes/report_form_mail.php",
data: data,
cache: false,
success: function (html) {
if (html == "true") {
form.find('.done').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
here is my mailing script, which is also placed in the separate file and named report_form_mail.php in my incudes folder
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// If valid, store values in variables
$site = "mySite.com";
$email = "donotreply#mySite.com";
$mes = stripslashes($_POST['message']);
$subject = "404 Alert";
$headers = "Content-Type: text/plain"."\n";
$headers .= "From: ".$site." <".$email.">"."\n";
$message = "Message: $mes";
// Send email
$sent = mail($email, $subject, $message, $headers);
if($sent) {
echo json_encode(true);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
Please help me to figure it all out
I have actually found an error myself.
The jQuery was not loaded to the page correctly so I have corrected it and my form works perfectly fine.
Thanks to all
I am using a jQuery Mobile Form script I found online. Everything is working fine, except the input="radio" buttons. I am not a jQuery expert by any means, so I am hoping someone here can help me.
THE SETUP
The form script contains 3 files: send.php, contact.js, and the mobile markup. Examples of the problematic pieces of code are below:
Mobile Markup:
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Doctor Type:</legend>
<input type="radio" name="doctortype" id="dmd" value="dmd"/>
<label for="dd">D.D.</label>
<input type="radio" name="doctortype" id="dds" value="dds" />
<label for="do">D.O.</label>
</fieldset>
</div>
Contact.js
$('#send-feedback').live("click", function() {
var url = 'api/send.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form');
$('.required', $contactform).each(function (i) {
if ($(this).val() === '') {
error++;
}
}); // each
if (error > 0) {
alert('Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk *.');
} else {
var doctortype = $contactform.find('input[name="doctortype"]').val();
var firstname = $contactform.find('input[name="firstname"]').val();
var surname = $contactform.find('input[name="surname"]').val();
var dob = $contactform.find('input[name="dob"]').val();
var zip = $contactform.find('input[name="zip"]').val();
var how = $contactform.find('select[name="how"]').val();
var email = $contactform.find('input[name="email"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type: "GET",
url: url,
data: {doctortype:doctortype, firstname:firstname, surname:surname, dob:dob, zip:zip, how:how, email:email, message:message},
success: function (data) {
if (data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Unable to send your message. Please try again.');
}
}
}); //$.ajax
}
return false;
});
Send.php
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["firstname"])) {
$doctortype = strip_tags($_GET['doctortype']);
$firstname = strip_tags($_GET['firstname']);
$surname = strip_tags($_GET['surname']);
$dob = strip_tags($_GET['dob']);
$zip = strip_tags($_GET['zip']);
$how = strip_tags($_GET['how']);
$email = strip_tags($_GET['email']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'MYEMAIL#gmail.com';
$subject = 'Contact Form';
$mailbody = "
Doctor Type: $doctortype
First Name: $firstname
Last Name: $surname
Date of Birth: $dob
Zip Code: $zip
How Did You Learn About Us: $how
Message: $message
IP: $ip
Browser info: $httpagent
Referral: $httpref
Sent: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>
THE RUB
The form works fine by itself. User fills out info, clicks "Send", and I receive an email with the information. However, I am not able to get the value of the checked radio to parse and send.
I've spent numerous hours trying to get the checked radio value to pass through the necessary steps.
And therein lies the problem. I've looked at countless similar posts on SO and other various places online, including the jQuery Mobile documentation. To no avail.
Any help is much appreciated!
What is your jQuery doing? It seems unnecessary to do any jQuery/JavaScript. The form should send the value of your radio button to $_GET['doctortype'] without it (assuming your form method is get).
*EDIT / FINISHED SOLUTION / WORKING CODE
So, this is what a friend of mine helped me come up with.
Here is the part I use in my K2 "items.php" file:
<div class="fb-comments" data-href="<?php echo JURI::current(); ?>" data-num-posts="8" notify="true" data-width="580"></div>
<input id="authname" style="display: none;" type="text" value="<?php echo $this->item->author->name; ?>" />
<input id="authmail" style="display: none;" type="text" value="<?php echo $this->item->author->email; ?>" />
<input id="link" style="display: none;" type="text" value="<?php echo JURI::current(); ?>" />
<script>
window.fbAsyncInit = function() {
FB.Event.subscribe('comment.create', function (response) {
var commentQuery = FB.Data.query("SELECT text, fromid FROM comment WHERE post_fbid='" + response.commentID +
"' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url='" + response.href + "')");
var userQuery = FB.Data.query("SELECT name FROM user WHERE uid in (select fromid from {0})", commentQuery);
FB.Data.waitOn([commentQuery, userQuery], function () {
var commentRow = commentQuery.value[0];
var userRow = userQuery.value[0];
console.log(userRow.name + " (id: " + commentRow.fromid + ") posted the comment: " + commentRow.text);
trackcomments(response['commentID'], response['href'], 'create', commentRow.text, userRow.name, commentRow.fromid);
});
});
};
function trackcomments(_commentid, _address, _action, _commentMessage, _userName, _userId) {
var authname = document.getElementById('authname').value;
var authmail = document.getElementById('authmail').value;
var link = document.getElementById('link').value;
$.ajax({
type: 'POST',
url: 'http://mydomain.com/dostuff.php',
data: {'commentMessage': _commentMessage, 'userName': _userName, 'authname': authname, 'authmail': authmail, 'link': link},
cache: false
});
};
</script>
And this is the do_stuff.php:
<?php
//Handle some weird letters and stuff
setlocale(LC_TIME, 'swedish');
//creating an $author variable and populating it from $_POST
$author = $_POST['authname'];
$authoremail = $_POST['authmail'];
$link = $_POST['link'];
$commentMessage = $_POST['commentMessage'];
$userName = $_POST['userName'];
$date = strftime('%A %e %b %Y %H.%M', time());
//getting author email
$to = $authoremail;
//subject of email
$subject = "New comment posted on mydmomain.com";
//email content
$message = "On $date $userName wrote\n\n$commentMessage\n\non your entry $link#comments\n\nUse the above link to answer on the comment.";
//who the mail is from
$from = "admin#mydomain.com";
//header
$headers = "From:" . $from;
//send the email
mail($to,$subject,$message,$headers);
?>
Turns out, there was a simple reason it wasn't working... JavaScript doesn't seem to handle PHP!
So the "do_stuff.php" (earlier named sendmail.php) was never executed with the echo JURI::base();.
Even then though. The var = $this->item... was also trying to get data from PHP variables which wasn't working. So, to combat that the values of those variables where put in hidden input forms to retrieve them thru getObjectById.
Like my friend stated, don't know if this is the most elegant or sophisticated solution... but it does the trick and fills it's purpose.
However, if someone has a better more "correct" way of achieving this, I'm all ears :)
Thank you #jack for your help! And anyone else contributing to this subject in the future.
- ORIGINAL POST -
Still learning about PHP and Joomla and K2. Been sitting upp for days now trying to figure out how I can have specific authors receive emails when comments are made using fb:comments.
So far so good...
FB.event.subscribe comment.create acting without action from user
Now, the only thing missing is the referens to the variable "$item->author->name". Since this is usable in the original file (item.php) where I'm calling for the sendmail.php
<script>
window.fbAsyncInit = function() {
/* All the events registered */
FB.Event.subscribe('comment.create', function (response) {
$.get('<?php echo JURI::base(); ?>sendmail.php');
});
};
</script>
and this is the "sendmail.php" file
<?php
if ($item->author->name == "Firstname1 Lastname1"){
$to = "author1#mydomain.com";
}else if ($item->author->name == "Firstname2 Lastname2"){
$to = "author2#mydomain.com";
};
$subject = "New comment";
$message = "A new comments has been made.";
$from = "admin#mydomain.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
I don't know how I can get the $item->author->name to work. Since I need to make sure that it somehow checks to see what the name is (since it's showing on the generated page I have to be able to use it somehow) to specify which email to send TO.
I have no idea if this has already been asked, but I don't even know what to search for to get me started here. I can't imagine that this would be to difficult to solve (if you only know what you need to change). :)
You can try passing the author name as a parameter in your ajax call. Something along these lines:
FB.Event.subscribe('comment.create', function (response) {
var name = $item->author->name;
$.get('<?php echo JURI::base(); ?>sendmail.php'), new {'authorName': name};
});
Then in your sendmail script you should be able to access the passed authorName parameter...
if (authorName == "Firstname1 Lastname1"){...
You could also use $.post to send the parameter to the sendmail script.
Note: This is untested and from memory, but hopefully it will point you in the right direction. It's also been a while since I last worked with Joomla, and there is likely a better Joomla-specific way to accomplish this.
EDIT: here's an example of using POST to pass the variable to the sendmail script:
FB.Event.subscribe('comment.create', function (response) {
var name = $item->author->name;
$.ajax({
type: "POST",
url:'<?php echo JURI::base(); ?>sendmail.php'),
data: authorName,
cache: false,
});
});
...and in your sendmail.php file:
<?php
//creating an $author variable and populating it from $_POST
$author = $_POST['authorName'];
if ($author == "Firstname1 Lastname1"){
$to = "author1#mydomain.com";
}else if ($author == "Firstname2 Lastname2"){
$to = "author2#mydomain.com";
};
$subject = "New comment";
$message = "A new comments has been made.";
$from = "admin#mydomain.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
Again this is untested, but should give you an idea. Since you're using Joomla you should also look into Joomla's com_mailto component, it may or may not be easier. You can search for further info with "pass parameter to external PHP script via ajax" or something along those lines.
Also, here's a reference for jQuery ajax
So I've read the jQuery AJAX pages, and a bunch of tutorials, but am having a slight problem over here.
There are no errors, or warnings, just a blank page.
I am trying to send an email when the user fills in the newsletter subscription test field with their email address, and when you click submit, the page refreshes! (1st problem) and it fails to display anything on the page (second problem), all you see is just a blank page. No emails were received.
I've tested the email script separately, which works fine. I've been using for months with different sites so I know it works.
I've tried changing things around in jQuery etc but nothing has helped fix this problem.
jQuery:
$(function () {
var txt = $('.email').val();
$.ajax({
url: 'index.php',
type: 'post',
data: {
email: txt
},
success: function (data) {
alert(data);
},
error: function (err, req) {
$('#Response').html({
"Somethin' got broked. Please try again."
});
}
});
});
PHP:
<?php
if($_POST["email"] != null)
{
require_once "Mail.php";
$email = $_POST["email"];
// Send it.
$from = "X#X.com.au";
$to = $email;
$subject = "Newsletter Subscription Request.";
$body = "Thank you for subscribing to our newsletter!";
$host = "mail.X.com.au";
$username = "no-reply#X.com.au";
$password = "X";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
}
?>
HTML:
<h4 id="Response">Stay informed. Subscribe to our Newsletter!</h4>
<form class="newsletterForm" action="index.php" method="post">
<input type="text" class="email" name="email" />
<input type='submit' class="btn" value="Subscribe" />
</form>
Can someone please help me figure out why this won't work?
Thank you
The 1st thing I do when stuff like this isn't working is to watch the page calls in the Chrome Developer Tools window.
As far as your code goes, the reason the page is refreshing is because the form submit is going through. To keep that from happening, you have to trap the form submit:
$("form").submit(function() {
// Do ajax
return false; // Keeps the form from submitting
});
Once you have that in place, you should be getting better results.
I would caution, however, that it is much easier to get the PHP email sending form working without using ajax at first by just having it handle the regular form submit. Once that works, then tie in the ajax on top of it.
With the following line you suppose to receive an answer from the PHP Script
success: function(data) {
alert(data);
}
But in the PHP script you don't output anything...Try writing something like
//[...]
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
die(1);
please try this surely you can get the problem solve.
function FormSubmit()
{
$.ajax({
type: "POST",
url: 'index.php',
data: $("#form_main").serialize(),
async: false
}).done(function( data ) {
$("#Response").hide();
if (isNaN(data))
{
dispmsg = "<div class='alert alert-danger' role='alert'>Oops..Something had gone wrong! Please try again!</div>";
$("#assess_me_response").html(dispmsg);
setTimeout('ResetForm();',3000);
}
else
{
dispmsg = "<div class='alert alert-success' role='alert'>Thank you for sharing the details. Our Consultant will contact you shortly!</div>";
$("#assess_me_response").html(dispmsg);
setTimeout('Redirect();',3000);
}
return true;
});
}
make your php as this..
<?php
$to = "xxxx#some.com";
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
$phone = $_POST['phone'];
$subject = "Entry received";
$msg = "\n Name:" . $name . "\n Email id:" . $email ."\n Age:". $age . "\n Contact number: " . $phone;
$headers = "From:xxx#yyy.com";
mail($to,$subject,$msg,$headers);
echo "<div align='center'>Thank you " . $name . "!, we will contact you shortly.</div>";
?>
try this you can solve.