I'm working on a contact form for a website using an jQuery Ajax call method that then uses WordPress's building in admin-ajax.php to submit the form's values, send them to an email address via wp_mail and then, if successful, send back an array through json_encode. The form works and the email sends but the success data isn't send after and the Ajax :success function doesn't initiate.
This has worked on other sites and I'm not sure why it's not working on this site. It send the email, just my jQuery method gets no success callback.
Here's what I've been using.
jQuery
(document).ready(function($){
$.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");
$.validator.addMethod("phoneNum", function(value, element) {
return this.optional(element) || /^[0-9\-\s]+$/i.test(value);
}, "Phone number can only be number and dashes.");
$("#contact-form").validate({
rules: {
name: {
required:true,
lettersonly: true
},
email: {
required: true,
email: true
},
phone: {
phoneNum: true,
},
message: {
required:true
}
},
messages: {
name: {
required: "Please enter your name.",
lettersonly: "Needs to be letters, no numbers please."
},
email: {
required: "Please enter your email adress.",
email: "Please enter your valid email adress."
},
phone: {
},
message:{
required: "Please enter a message.",
}
},
submitHandler: function(form) {
$('#contact-msg').html('<p class="ajaxLoader">Sending Email...</p>');
$.ajax ({
type: 'POST',
url: ajax_object.ajax_url,
data: $('#contact-form').serialize(),
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('#contact-form')[0].reset();
}
$('#contact-msg').html(response.errmessage);
}
});
}
});
});
Function.php
// CONTACT FORM SCRIPTS
function contactform_add_script() {
wp_enqueue_script( 'contactform-script', get_template_directory_uri().'/assets/js/contact_me.js', array('jquery') , null, true);
wp_localize_script( 'contactform-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'contactform_add_script');
// CONTACT FORM PROCESSING
function ajax_contactform_action_callback() {
$error = '';
$status = 'error';
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
$error = 'All fields are required to enter.';
} else {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$number = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
// $treatments = filter_var($_POST['treatments'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$subject = 'A message from St. Romain Interiors\'s contact form.';
$message .= PHP_EOL.'Sender\'s name: '.$name;
$message .= PHP_EOL.'Phone number: '.$number;
$message .= PHP_EOL.'E-mail address: '.$email;
$message .= PHP_EOL.'Message: '.stripslashes($_POST['message']);
$sendmsg = "Thanks for the message! We will respond as soon as possible.";
$to = '[email protected]'; // If you like change this email address
// replace "[email protected]" with your real email address
$header .= 'Reply-To: '.$email.PHP_EOL;
if ( wp_mail($to, $subject, $message, $header) ) {
$status = 'success';
$error = $sendmsg;
} else {
$error = 'Some errors occurred.';
}
}
$resp = array('status' => $status, 'errmessage' => $error);
header( "Content-Type: application/json" );
echo json_encode($resp);
die();
}
add_action( 'wp_ajax_contactform_action', 'ajax_contactform_action_callback' );
add_action( 'wp_ajax_nopriv_contactform_action', 'ajax_contactform_action_callback' );
UPDATE!
If I replace the submitHandler with this it returns the sentence, but now the email is never sent...
submitHandler: function(form) {
$('#contact-msg').html('<p class="ajaxLoader">Sending Email...</p>');
$.ajax ({
type: 'POST',
url: ajax_object.ajax_url,
data: { action: "contactform_action",
values: $('#contact-form').serialize() },
dataType: 'json',
success: function(response) {
$('#contact-msg').html('<p>Thanks for the message!</p>');
}
});
}
UPDATE #2
I replaced the success function with the original from the first post, but kept the data values you suggested and it's doing the same old thing, sending the email but not sending a success callback. On Mozilla Firebug I was able to find this information in the Response Headers panel.
X-Robots-Tag: noindex
X-Powered-By: PHP/5.6.14
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
Transfer-Encoding: chunked
Server: Apache
Pragma: no-cache
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Date: Mon, 26 Oct 2015 06:13:54 GMT
Content-Type: application/json
Cache-Control: no-cache, must-revalidate, max-age=0
UPDATE #3
Here's the response I see in Firebug
<br />
<b>Notice</b>: Undefined index: name in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>156</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>157</b><br />
<br />
<b>Notice</b>: Undefined index: phone in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>158</b><br />
<br />
<b>Notice</b>: Undefined variable: message in<b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>161</b><br />
<br />
<b>Notice</b>: Undefined index: message in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>165</b><br />
<br />
<b>Notice</b>: Undefined variable: header in <b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>171</b><br />
{"status":"success","errmessage":"Thanks for the message! We will respond as soon as possible."}
I'm working on a contact form for a website using an jQuery Ajax call method that then uses WordPress's building in admin-ajax.php to submit the form's values, send them to an email address via wp_mail and then, if successful, send back an array through json_encode. The form works and the email sends but the success data isn't send after and the Ajax :success function doesn't initiate.
This has worked on other sites and I'm not sure why it's not working on this site. It send the email, just my jQuery method gets no success callback.
Here's what I've been using.
jQuery
(document).ready(function($){
$.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");
$.validator.addMethod("phoneNum", function(value, element) {
return this.optional(element) || /^[0-9\-\s]+$/i.test(value);
}, "Phone number can only be number and dashes.");
$("#contact-form").validate({
rules: {
name: {
required:true,
lettersonly: true
},
email: {
required: true,
email: true
},
phone: {
phoneNum: true,
},
message: {
required:true
}
},
messages: {
name: {
required: "Please enter your name.",
lettersonly: "Needs to be letters, no numbers please."
},
email: {
required: "Please enter your email adress.",
email: "Please enter your valid email adress."
},
phone: {
},
message:{
required: "Please enter a message.",
}
},
submitHandler: function(form) {
$('#contact-msg').html('<p class="ajaxLoader">Sending Email...</p>');
$.ajax ({
type: 'POST',
url: ajax_object.ajax_url,
data: $('#contact-form').serialize(),
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('#contact-form')[0].reset();
}
$('#contact-msg').html(response.errmessage);
}
});
}
});
});
Function.php
// CONTACT FORM SCRIPTS
function contactform_add_script() {
wp_enqueue_script( 'contactform-script', get_template_directory_uri().'/assets/js/contact_me.js', array('jquery') , null, true);
wp_localize_script( 'contactform-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'contactform_add_script');
// CONTACT FORM PROCESSING
function ajax_contactform_action_callback() {
$error = '';
$status = 'error';
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) {
$error = 'All fields are required to enter.';
} else {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$number = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
// $treatments = filter_var($_POST['treatments'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$subject = 'A message from St. Romain Interiors\'s contact form.';
$message .= PHP_EOL.'Sender\'s name: '.$name;
$message .= PHP_EOL.'Phone number: '.$number;
$message .= PHP_EOL.'E-mail address: '.$email;
$message .= PHP_EOL.'Message: '.stripslashes($_POST['message']);
$sendmsg = "Thanks for the message! We will respond as soon as possible.";
$to = '[email protected]'; // If you like change this email address
// replace "[email protected]" with your real email address
$header .= 'Reply-To: '.$email.PHP_EOL;
if ( wp_mail($to, $subject, $message, $header) ) {
$status = 'success';
$error = $sendmsg;
} else {
$error = 'Some errors occurred.';
}
}
$resp = array('status' => $status, 'errmessage' => $error);
header( "Content-Type: application/json" );
echo json_encode($resp);
die();
}
add_action( 'wp_ajax_contactform_action', 'ajax_contactform_action_callback' );
add_action( 'wp_ajax_nopriv_contactform_action', 'ajax_contactform_action_callback' );
UPDATE!
If I replace the submitHandler with this it returns the sentence, but now the email is never sent...
submitHandler: function(form) {
$('#contact-msg').html('<p class="ajaxLoader">Sending Email...</p>');
$.ajax ({
type: 'POST',
url: ajax_object.ajax_url,
data: { action: "contactform_action",
values: $('#contact-form').serialize() },
dataType: 'json',
success: function(response) {
$('#contact-msg').html('<p>Thanks for the message!</p>');
}
});
}
UPDATE #2
I replaced the success function with the original from the first post, but kept the data values you suggested and it's doing the same old thing, sending the email but not sending a success callback. On Mozilla Firebug I was able to find this information in the Response Headers panel.
X-Robots-Tag: noindex
X-Powered-By: PHP/5.6.14
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
Transfer-Encoding: chunked
Server: Apache
Pragma: no-cache
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Date: Mon, 26 Oct 2015 06:13:54 GMT
Content-Type: application/json
Cache-Control: no-cache, must-revalidate, max-age=0
UPDATE #3
Here's the response I see in Firebug
<br />
<b>Notice</b>: Undefined index: name in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>156</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>157</b><br />
<br />
<b>Notice</b>: Undefined index: phone in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>158</b><br />
<br />
<b>Notice</b>: Undefined variable: message in<b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>161</b><br />
<br />
<b>Notice</b>: Undefined index: message in <b>/home/theski/public_html/stromain/wp-content/themes/stromain
/functions.php</b> on line <b>165</b><br />
<br />
<b>Notice</b>: Undefined variable: header in <b>/home/theski/public_html/stromain/wp-content/themes
/stromain/functions.php</b> on line <b>171</b><br />
{"status":"success","errmessage":"Thanks for the message! We will respond as soon as possible."}
Share
Improve this question
edited Apr 25, 2018 at 12:29
Ciprian
8802 gold badges11 silver badges27 bronze badges
asked Oct 25, 2015 at 4:27
Jacob BullerJacob Buller
11 silver badge5 bronze badges
2 Answers
Reset to default 0You are not giving the action name to your AJAX call. In WordPress, you have to give an action name, the same name you give whatever is after wp_ajax_ and wp_ajax_nopriv_
In this case, the AJAX call should work if you change the data: inside your AJAX call, for this:
data: {action: "contactform_action", values: $('#contact-form').serialize()}
Then retrieve the values of the form with $_POST["values"];
in your php function.
The answer was that debug was set to 'true' in wp_config. This created error html to be returned by Wordpress because variables in the functions.php were being assigned via ajax but Wordpress debug was reporting them as 'Undefined'. I found this out by viewing the return information on the console tab in Firebug when submitting content on the form. The return was filled with
and Undefined errors. This caused the AJAX response to break, not allowing me activate the ajax callback. Setting wp_config debug to 'false' fixed everything.
At least this is what I'm assuming, please correct me if I'm wrong.