1

I'm building custom contact form on wordpress using jquery $.post() function.

$.post(tmpl_dir + '/bugreport.php',{ name:name, email:email, message:message }, function(data) {
                if ( data ) alert( 'thanks for answer' )
                else alert('error sending, please try again.');

            })

(tmlp_dir is theme directory path)

here is bugreport.php file:

<?php 
if ( isset($_POST['name']) && isset($_POST['email']) &&isset($_POST['message']) ) {
    $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message'];
    $send_to = "mail@mail.com";
    $subject = "Question from " . $name;
    $success = wp_mail($send_to,$subject,$message);
            if ($succsess) return true
            else return false;
}
?>

I'm getting an error from wordpress that says: wp_mail() function not defined. How can i let my php file use wp_mail() function?

Thanks.

aleXela
  • 1,270
  • 2
  • 21
  • 34

1 Answers1

2

You should use the wordpress ajax hook in order to get wordpress classes.

http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

I would recommend cleaning the code a bit and adding a Nonce check, but your code should look something like this:

js:

jQuery.post(
    MyAjax.ajaxurl, 
    {
        'action': 'send_message',
        'name':'name', 
        'email':'email', 
        'message':'message'
    }, 
    function(response){
        alert('The server responded: ' + response);
    }
);

php:

add_action( 'wp_ajax_send_message', 'do_send_message' );

function do_send_message() {

  if ( isset($_POST['name']) && isset($_POST['email']) &&isset($_POST['message']) ) {
    $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message'];
    $send_to = "mail@mail.com";
    $subject = "Question from " . $name;
    $success = wp_mail($send_to,$subject,$message);
            if ($succsess) return true
            else return false;
  }

}

To load your js file and vars add this to functions.php or your plugin.

$myvars = array( 
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
);
wp_enqueue_script( 'my-ajax-request', plugins_url( '/path/to/somefile.js', __FILE__ ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', $myvars );
GGG
  • 817
  • 5
  • 6
  • Thanks, and what about just `include(wp-load.php)`? – aleXela Jul 25 '13 at 05:53
  • yo need to declare it when you add your script, you can do so using something like this: wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); – GGG Jul 26 '13 at 04:04
  • I have edited the answer to add instructions for the wp_enqueue_script – GGG Jul 26 '13 at 19:49
  • You used `wp_enqueue_script( 'my-ajax-request', plugins_url( '/path/to/somefile.js', __FILE__ ) );` plugins_url function. My javascript files not in plugins folder. – aleXela Jul 28 '13 at 14:45
  • It should be `get_template_directory_uri()` instead. – aleXela Jul 28 '13 at 14:46