简体   繁体   中英

Wordpress wp_mail function error in template via ajax

I have created a WordPress template which has the capability of sending emails via ajax and the wp_mail function. The everything is okay apart from the wp_mail function which gives a false response and therefore the email is not sent. I have tried researching for a possible solution for almost a week now but no success. Below is my code, hope you can help me figure out where the issue is. The error displayed is on this line

throw new Exception('Failed to send email. Check AJAX handler fruu.');

located in the functions.php file.

template functions.php file

wp_enqueue_script('jquery');
function makeBooking() {
    try {
       if (empty($_POST['start']) || empty($_POST['names']) || empty($_POST['email']) || empty($_POST['bphone']) || empty($_POST['adult']) || empty($_POST['child'])) {
         throw new Exception('Bad form parameters. Check the markup to make sure you are naming the inputs correctly.');
       }
       if (!is_email($_POST['email'])) {
          throw new Exception('Kindly enter a valid email.');
       }

       $e = explode(" - ", $_POST['start']);
       $date1 = new DateTime($e['0']);
       $date2 = new DateTime($e['1']);
       $diff = $date2->diff($date1)->format("%a");
       if(($diff < '2') ? $s='': $s='s');
       if (($_POST['adult'] < '2') ? $ss = '' : $ss = "s");
       if ($_POST['child'] == 'no') {
           $cs = "No Children";
       } else {
           if ($_POST['child'] < '2') {
                $cs = "1 Child";
           } else {
                $cs = $_POST['child'].' Children';
           }
       }
       if ($_POST['req'] == '') {
           $req = "";
       } else {
           $req = " \n\nSpecial Request: ".$_POST['req'];
       }

       $subject = 'New Booking Request from: '.$_POST['names'];
       $headers = 'From: '.$_POST['names'].' <'.$_POST['email'].'>';
       $send_to = "booking@mysite.com";
       $message = "Booking Duration: ".$diff." day".$s." from ".date("l M dS, Y", strtotime($e['0']))." to ".date("l M dS, Y", strtotime($e['1']))." \n\nBooking Party: ". $_POST['adult'] . " Adult".$ss." and ".$cs.". \n\nContact Number: +" . $_POST['bphone']."".$req;
       if (wp_mail($send_to, $subject, $message, $headers)) {
           echo json_encode(array('status' => 'success', 'message' => 'Contact message sent.'));
           exit;
       } else {
           throw new Exception('Failed to send email. Check AJAX handler fruu.'); //THIS IS THE ERROR THAT IS RETURNED BY THE SCRIPT
       }
   } catch (Exception $e) {
       echo json_encode(array('status' => 'error', 'message' => $e->getMessage()));
       exit;
   }
}
add_action("wp_ajax_makeBooking", "makeBooking");
add_action('wp_ajax_nopriv_makeBooking', 'makeBooking');

The Form

<form class="contact modal-form" name="contact" id="booking_form">
<input type="hidden" name="form_send" value="send" />
<input required class="col-lg-12 form-control" name="start" id="start" placeholder="Duration of Stay" type="text">
<input required class="col-lg-12 form-control" name="end" id="end" value="" placeholder="Departure Date" type="text">
<input required class="form-control col-lg-12" name="names" id="names" value="" placeholder="Full Names" type="text">
<input required class="form-control col-lg-12" name="email" id="email" value="" placeholder="Email Address" type="email">
<input required class="form-control col-lg-12" name="bphone" id="bphone" value="" placeholder="Phone Number (e.g 2547xx 123xx4)" type="tel">
<select required style="" class="col-lg-12 form-control" name="adult" id="adult">
<option selected="selected" value="">Adults</option>
<?php
    echo '<option value="1">1 Adult</option>';
    $i = '2';
    while ($i < '11') {
        $k = $i;
        echo '<option value="'.$k.'">'.$k.' Adults</option>';
        $i++;
    }
?>
</select>
<select required style="" class="col-lg-12 form-control" name="child" id="child">
<option selected="selected" value="">Children</option>
<?php
    echo '<option value="no">No Children</option>';
    echo '<option value="1">1 Child</option>';
    $i = '2';
    while ($i < '11') {
        $k = $i;
        echo '<option value="'.$k.'">'.$k.' Children</option>';
        $i++;
    }
?>
</select>
<textarea class="form-control col-lg-12" name="req" id="req" placeholder="Special Request"></textarea>
<input type="hidden" name="action" value="makeBooking" />
<button class="btn btn-success" type="submit" id="sendBooking"><i class="fa fa-spinner fa-pulse fa-fw hide fa-2x" id="sending"></i><span id="text" class=''>Send</span></button>
</form>

jQuery Code and please note I have left out the code with the data validation rules

$('#sendBooking').click(function(e) {
$.ajax({
    url:"/wp-admin/admin-ajax.php",
    type:'POST',
    dataType: 'JSON',
    data:$("#booking_form").serialize(),
    cache: false,
    success: function(data){ 
        show_ok(data);
    },
    error: function(){                      
        $("#sending").addClass("hide");
        $("#text").removeClass("hide");
        $("#sendBooking").removeClass("disabled");
        $("#msg_not_sent").removeClass("hide");
    }
});
e.preventDefault();
});

Thanks in advance.

Make sure all serialize data you are getting in ajax call.if require use PHP unserialize function:

parse_str($_POST["data"], $_POST);

Then change

 $send_to = "booking@mysite.com";

to your actual email and check it again.

I discovered the source of my error after weeks of research. So, the issue is based on PHP rather than the code. As it turns out, the from address has to be similar to the domain name, that is, if the domain name is example.com, the from address has to be email@example.com. If the from address is name@email.com, the connection will be closed by the server automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM