I'm developing a form template within a wordpress theme. I need the form data to be sent via email to a certain address via AJAX. Here is the form handling in JS:
var FormData = function(){
var user_name;
var user_email;
var user_message;
this.setName = function(name){
this.user_name = name;
}
this.getName = function(){
return this.user_name;
}
this.setEmail = function(email){
this.user_email = email;
}
this.getEmail = function(){
return this.user_email;
}
this.setMessage = function(message){
this.user_message = message;
}
this.getMessage = function(){
return this.user_message;
}
this.nameIsValid = function(){
if(this.user_name != ''){
return true;
} else {
return false;
}
}
this.emailIsValid = function(){
if(this.user_email != ''){
return true;
} else {
return false;
}
}
this.messageIsValid = function(){
if(this.user_message != ''){
return true;
} else {
return false;
}
}
this.formIsValid = function(){
if((this.nameIsValid() && this.emailIsValid() && this.messageIsValid())){
return true;
} else {
return false;
}
}
};
$(document).ready(function(){
user_object = new FormData();
});
Some may find it unnecessary to validate a form. But I did it just for study purposes anyway. Omitting the methods that I believe do not make any difference, I press on.
$('#form-contact').submit(function(e){
e.preventDefault();
user_object.setName($('input[name=user_name]').val());
user_object.setEmail($('input[name=user_email]').val());
user_object.setMessage($('#user_message_textarea').val());
if(user_object.formIsValid()){
var formData = JSON.stringify(user_object);
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
url: '/wp-admin/admin-ajax.php',
data: formData,
success: function(data){
alert(data);
$('#form-contact').trigger('reset');
},
error: function(){
alert("Deu erro aqui!");
}
});
} else {
alert("Este formulário não é válido!");
}
I want to send the object in Ajax notation pro PHP method. Now the server-side code:
function sendMail(){
$obj = json_decode($_POST['formData']);
$user_name = $obj->{'user_name'};
$user_email = $obj->{'user_email'};
$user_message = $obj->{'user_message'};
$send = mail('[email protected]', 'Contato pelo Site', $user_message);
if ($send) {
return json_encode("Certinho!");
} else {
return json_encode("Deu erro!");
}
}
add_action('wp_ajax_sendMail', 'sendMail');
add_action('wp_ajax_nopriv_sendMail', 'sendMail');
Now the problem! When I submit the form, I debug the AJAX request, and it is giving status 200. Including, I get the success message in response. However, the PHP function is not actually executed and I do not get any email.
Where did I go wrong?