简体   繁体   中英

No email sent with Ajax contact form (in Wordpress)

I'm trying to build a simple Ajax contact form in Wordpress, with validation (jQuery Validate plugin) with this code:

Html

<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; 
</script>

Js

$("#form").validate({  //jquery validate plugin

    ... // rules

    submitHandler: function(form) {

    var data = $('form').serialize();

        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: data,        
            cache: false,
            action: 'sendmail',

            success: function (html) {           
                ... // succesful message         
            }
        }); 

        return false;

    } // end submitHandler

}); // end Validate

function.php

function send_my_mail(){
    ... //sends email
}
add_action('wp_ajax_sendmail', 'send_my_mail');
add_action('wp_ajax_nopriv_sendmail', 'send_my_mail');

When I submit the form the browser console retrieves this ok message:

POST http://www.domain.com/wp-admin/admin-ajax.php 200 OK 3.45s 

but no email was sent. I don't get what's wrong in the code!

The problem is that you use an "action" option that doesnt exists in jQuery.ajax. You just need to pass the action to WP in the data option like this :

$("#form").validate({  //jquery validate plugin

    ... // rules

    submitHandler: function(form) {

    var data = $('form').serialize();

        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: data + '&action=sendmail',        
            cache: false,

            success: function (html) {           
                ... // succesful message         
            }
        }); 

        return false;

    } // end submitHandler

}); // end Validate

Why don't you use wp_mail function?

Also use a different SMTP connection if it doesn't work. You can test with gmail SMTP to see if that is the problem with SMTP you are using.

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