I'm trying to send email from WP using ajax to validate the form and wp_mail to send the mail.

The form is a basic form with id names on the fields

The js validtion looks like this

      $('#submit').click(function(e) {
        if(verfiyFields()) {
          requestData = {
            'action' : 'myajax-submit',
            'firstName' : $("#name").val(), 
            'email' : $("#email").val(), 

          $.post(MyAjax.ajaxurl, requestData).done(function(result){        
            //result = jQuery.parseJSON( result );
            if(result ==  'success'){

    function verfiyFields() {
      var flag = true;

      var name =        $('#name');
      var email =       $('#email');

      if(name.val().indexOf(' ') === -1 ){
        name.parent().prepend('<p class="form-error">Please enter name, first space last</p>');
        flag = false;
        email.parent().prepend('<p class="form-error">Please enter valid email address</p>');
        flag = false;
      return flag;

I'm using grunt to concate and minify the js so I'm enqueue the js script which includes the validation in the functions.php like this.

    add_action( 'wp_enqueue_scripts', 'add_my_script' );

    function add_my_script() {
        wp_register_script('scripts',get_template_directory_uri() . '/js/compiled/main.min.js', array('jquery'),1 ,true);


        wp_localize_script( 'scripts', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));

and the myajax_submit function like this.

    add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );

    function myajax_submit() {
        // get the submitted parameters

        $name = sanitize_text_field($_POST['firstName']);
        $email = sanitize_text_field($_POST['email']);

        $headers[] = 'From: ' . $name . ' <' . $email . '>' . "\r\n";
        $headers[] = 'Content-type: text/html' . "\r\n"; //Enables HTML ContentType. Remove it for Plain Text Messages
        //$to = TRAINING_EMAIL;
        $to = 'me@mysite.co.uk';

        wp_mail( $to, $subject, $message, $headers );

        // generate the response
        $response = json_encode( array( 'success') );

        // response output
        header( "Content-Type: application/json" );
        echo $response;

        // IMPORTANT: don't forget to "exit"

I'm using a correct email address in the $to variable.

If I test on a live server the valdation works.

In Chromes Network tab I can see the admin-ajax.php run and the header tab on the right shows a Status code of 200 OK

Does this mean the mail should have been sent - I don't get any email

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.