I am customizing a new theme for my wordpress locally. I have form for sending an email.but its not working. When i am trying with below code in my functions.php, i am getting 'email error!' instead of 'email sent successfully'
add_action('wp_ajax_enquiry','form_enquiry');
add_action('wp_ajax_nopriv_enquiry','form_enquiry');
function form_enquiry(){
$formdata=[];
wp_parse_str($_POST['enquiry'],$formdata);
$admin_email='[email protected]';
$headers[]='Content-Type:text/html; charset=UTF-8';
$headers[]='From: My Website <'.$admin_email.'>';
$headers[]='Reply-to:' .$formdata['email'];
$send_to=$admin_email;
$subject='Enquiry from '.$formdata['fname'].' '.$formdata['lname'];
$message='';
foreach($formdata as $index=>$field){
$message .= '<strong>'.$index.'</strong>:'.$field.'</br>';
}
try{
if(wp_mail($send_to,$subject,$message,$headers)){
wp_send_json_success('email sent successfully!');
}else{
wp_send_json_error('email error!');
}
}catch(Exception $e){
wp_send_json_error($e->getMessage());
}
}
Here the arguments passing to wp_mail() are valid one.But still it returns false. As i am new to this i didn't understand why it returns false instead of true. My form.php code is given below
<form id="enquiry">
-----
</form>
<script>
(function($){
$('#enquiry').submit(function(event){
event.preventDefault();
var endpoint= '<?php echo admin_url('admin-ajax.php') ?>'
var form= $('#enquiry').serialize();
var formdata = new FormData;
formdata.append('action','enquiry');
formdata.append('enquiry',form);
$.ajax(endpoint,{
type:'POST',
data:formdata,
processData:false,
contentType:false,
success: function(res){
alert(res.data);
},
error:function(err){
alert(err.responseJSON.data);
}
})
})
})(jQuery)
</script>
Am i going wrong?.Can anyone please help?