Wordpress Sending email through Ajax without page refresh hangs on admin_ajax.php

359 Views Asked by At

I have this test page on a website - https://piclits.com/test-slideshow/

It displays a bunch of images/PICLITS and grabs them randomly from a folder 12 at a time into a slideshow.

I want to email the main image without refreshing the page (which would bring up 12 new images) from the email button which opens up a popup to add email addresses.

All is good - I can grab the image and mail it but the script does something wacky where it flashes on the page and then hangs up at admin-ajax.php rather than just staying on the page and sending the email.

My Form:

<div class="ajax-form-container" style="float: left">
   <form id="ajaxformid" action="" method="POST">
       <p>Email this PIC-LIT to a friend.<br />You may include multiple emails if you separate them with a comma.</p>
       <ul style="list-style-type: none;">
           <li>Email: <textarea name="piclit_email" id="piclit_email" rows="4" cols="50" autofocus=""></textarea><input type="hidden" name="founder_piclit" id="founder_piclit" value=""></li>
           <li><input type="hidden" name="piclit_bcc" class="piclit_bcc" value="0"></li>
           <li>bcc: <input type="checkbox" name="piclit_bcc" class="piclit_bcc" value="1">
           <?php wp_nonce_field( 'fiveb_ajax_nonce', 'fiveb_nonce_field' ); ?></li>
           <li><input type="submit" name="submit" value="Send"></li> 
       </ul>
   </form>
   <div id="ajax_success" style="display: none">Email sent.</div>
   <div id="ajax_error" style="display: none">There was an error. Sorry your email was not sent.</div>
</div>

Javascript

<script>  
    jQuery('#ajaxformid').submit(function(e) {
        e.preventDefault();
        var piclit_email = jQuery( "#piclit_email" ).val();
        if (piclit_email == '') 
            alert("Please fill in all fields to send an email.");
        else {
            var founder_piclit = jQuery( "#founder_piclit" ).val();
            // alert (founder_piclit);
            var piclit_bcc = jQuery('.piclit_bcc').val();
            var formData = {
                piclit_email: piclit_email,
                founder_piclit: founder_piclit,
                piclit_bcc: piclit_bcc,
                action: 'fiveb_ajax_mail',
            };
            jQuery.ajax({
                type        : 'POST', 
                url         : '<?php echo admin_url( 'admin-ajax.php' ); ?>',
                dataType    : 'json',
                data        : formData,
            }).done(function(data) {
                console.log(data);
            }).fail(function(data) {
                console.log(data);
            });
        }
    });
</script>

and php:

function fiveb_function() {
    $subject = 'View A Founder PIC-LIT from piclits.com';
    $piclit_email = strval($_REQUEST['piclit_email']);
    $founder_piclit = strval($_REQUEST['founder_piclit']);
    $piclit_bcc = strval($_REQUEST['piclit_bcc']);
    if ($piclit_bcc) {
        $headers[] = 'Bcc: '.$piclit_email;
    }
    $message = '<html><head><title>Founder PIC-LIT</title></head><body><table border="0" cellspacing="2" cellpadding="20" bgcolor="#ffffff" width="100%"><tbody><tr><td></td><td width="600"><p style="text-align: center">Hello!<br />View A Founder PIC-LIT from <a href="https://piclits.com">piclits.com</a>.</p></td><td></td></tr><tr><td></td><td><img src="'.$founder_piclit.'" alt="Founder PIC-LIT" width="600" style="display:block;width:100%" /></td><td></td></tr></tbody></table></body></html>';
    $headers[] = 'From: PIC-LITS <[email protected]>';
    $headers[] = 'Content-Type: text/html; charset=UTF-8';
    if ($bcc) $sent_mail = wp_mail( "", "$subject", $message, $headers );
    else $sent_mail = wp_mail( "$piclit_email", "$subject", $message, $headers );
    if ($sent_mail) {
        echo ('email sent');
        die();
    } else { 
        echo ('There was an error. Sorry your email was not sent.');
        die();
    } 
}
add_action("wp_ajax_fiveb_function", "fiveb_function");
add_action("wp_ajax_nopriv_fiveb_function", "fiveb_function");

Seems like I am so close but I cannot get the script to stop hanging up on admin-ajax.php. Any help would be so appreciated! Maybe it has something to do with my popup? I am out of ideas

1

There are 1 best solutions below

4
On

Your code will look like this.

Note - Form action should be blank.

<form action="" method="POST" id="ajaxformid">

</form>
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
wp_localize_script( 'custom-js', 'fiveb_ajax_mail', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

add_action("wp_ajax_fiveb_ajax_mail", "fiveb_ajax_mail"); 
add_action("wp_ajax_nopriv_fiveb_ajax_mail", "fiveb_ajax_mail"); 
function fiveb_ajax_mail()
{
$formdata = $_post['formdata'];
wp_mail($to,$subject,$message,$header);
return 'true';
wp_die();
}
//add below js in custom.js file
    $('#ajaxformid').submit(function (e) {
       e.preventDefault();
       jQuery.ajax({
                type: "post",
                dataType: "json",
                url: fiveb_ajax_mail.ajax_url,
                data : {action: "fiveb_ajax_mail","formdata":"your form data variable place here"},
                success: function(msg){
                  console.log(msg);
                }
            });
    }

In my local system, it is working fine.