Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

need to send an email from a page when a form is submitted.

Thought i'd use jquery post but not really sure where to start. Would i use wp_mail? And if so how could it be called ?

Sorry if that seems vague. Just trying to send an email to the client before a form posts its data to another site;

$('#donationForm').submit(function() {

// send email to client before moving onto worldpay payment form


//  send data to worldpay....
this.submit();

});

best, Dc

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

Basically, you can use JavaScript to post to a WordPress function, then the WordPress function can invoke wp_mail() to send the message.

A great place to start would be the useful AJAX in Plugins article on the Codex. It walks you through all the steps required to add your JavaScript on the front-end, your PHP on the back-end, and everything you need to do to tie the two together.

share|improve this answer
add comment

First add your email processing function and hook it to wp_ajax hooks like this using your functions.php:

//if you want only logged in users to access this function use this hook
add_action('wp_ajax_mail_before_submit', 'send_AJAX_mail_before_submit');

//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_mail_before_submit', 'send_AJAX_mail_before_submit');

function send_AJAX_mail_before_submit(){
    check_ajax_referer('my_email_ajax_nonce');
    if (isset($_POST['action']) && $_POST['action'] =="mail_before_submit"){

    //send email  wp_mail( $to, $subject, $message, $headers, $attachments ); ex:
        wp_mail('email@domain.com','this is the email subject line','email message body');
        echo 'email sent';
        die();
    }
    echo 'error';
    die();
}

then inside you JQuery create the ajax call like this:

jQuery('#donationForm').submit(function() {

// send email to client before moving onto worldpay payment form
var data = {
    action: 'mail_before_submit',
    Whatever: 1234,
    _ajax_nonce: <?php echo wp_create_nonce( 'my_email_ajax_nonce' ); ?>
};
jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response) {
        alert('Got this from the server: ' + response);
});
//  send data to worldpay....
this.submit();

});

and you should be set.

share|improve this answer
    
thanks! got this working but had to remove '_ajax_nonce' as was causing error. Is it important? Dc –  daniel Crabbe Jun 1 '11 at 12:18
    
its the right way and bet practice to secure ajax calls. –  Bainternet Jun 1 '11 at 12:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.