• Resolved jennnjennjen

    (@jennnjennjen)


    I’m running up against a undefined function wp_mail() error I could use some help with.

    The script “approve_ajax” is enqueued via the following:

    add_action( 'wp_enqueue_scripts', 'approve_ajax' );
    function approve_ajax() {
    	wp_enqueue_script( 'approve_ajax', get_template_directory_uri() . '/list/ajax.js', array('jquery'), '1.0', true );
    }

    The contents of ajax.js are simple, basically onclick it is triggered, and calls the server-approve.php script:

    function approve(user,email) {
            $.ajax({
                url: "/wp-content/themes/bibliofile/list/server-approve.php",
                type: "POST",
                data: { 'username': user, 'approve': '1', 'emailaddress': email },     
              	success: function(data){ // there's some stuff here }
            }); 
        };

    Server-approve.php does a bunch of stuff but most importantly:
    if (isset($_POST['username'])) { wp_mail($_POST['emailaddress'], $subject, $message); }

    I can’t seem to figure out how to get wp_mail() to work here. I get a 500 server error each time. It works fine anywhere that doesn’t involve AJAX.

    • This topic was modified 5 years, 11 months ago by jennnjennjen.
    • This topic was modified 5 years, 11 months ago by jennnjennjen.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Your code invokes the PHP file directly, without using WordPress to do ajax, so none of the WordPress functions are available to that code. If you use WordPress ajax, then you can use all of the WordPress functions.

    Also, your URL is hard-coded, so it would not work in a multisite or a renamed theme or a subfolder installation.

    Thread Starter jennnjennjen

    (@jennnjennjen)

    Hi Joy thanks for the response.

    Yeah, I realize I’m not invoking it the way WordPress needs me to do it to get it to work, I just don’t understand what I need to do to fix it. If anyone has some pointers, would greatly appreciate it.

    • This reply was modified 5 years, 11 months ago by jennnjennjen.
    Moderator bcworkz

    (@bcworkz)

    Ajax for WP involves some very specific quirks that you must adhere to. Please review this page and the one after it.

    Thread Starter jennnjennjen

    (@jennnjennjen)

    OK got it to work. This guide was really helpful, if anyone else ever comes across this with the same issue.

    https://wpshout.com/crash-course-ajax-wordpress/

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Calling wp_mail() with AJAX’ is closed to new replies.