简体   繁体   中英

Send email via ajax once radio button is clicked

I am trying to send an email when someone clicks a radio button without having the page refresh. I've gotten the system to send emails with the value, it just refreshes everytime which I don't want. I am not the best with Ajax and Javascript, but any help would be much appreciated.

I've tried the e.preventDefault(); function as well but can't seem to get that to work either.

I'm running the site via a localhost on the WordPress platform. Below is the code I have:

PHP file for sending the email

if(isset($_POST['radio'])){
 $user_info = get_userdata(1);
 $email = $user_info->user_email;
 $to = "example@example.com";
 $from = "donotreply@example.org"; 
 $subject = "Subject";
 $message = "Option Clicked: " . $_POST['radio'] . "\nName: " . 
 $user_info->last_name .  ", " . $user_info->first_name . "\nUser Email: ". $email;
 $headers = "From:" . $from;    
    wp_mail($to,$subject,$message,$headers);
}

HTML

<form id="contact" action="unsubscribe.php" method="post" name="contact">
 <span class="close-button">&times;</span>
 <h3>Title</h3>
 <p>Description</p>
 <ul>
  <li>
   <input type="radio" name="radio" id="option1" value="Option 1" /><label for="option1">Option 1</label>
   <div class="check"></div>
  </li>
  <li>
   <input type="radio" name="radio" id="option2" value="Option 2" /><label for="option2">Option 2</label>
   <div class="check"></div>
  </li>
 </ul>
 <div id="button" class="hide">
  <a href="<?php echo esc_url($action['url']); ?>" class="unsubscribe-button button cancel">Submit and Cancel Subscription</a>
 </div>
</form>

JS

$('input[name$="radio"]').on('click', function(){
    var radio = $(this).val();
      $("#" + radio);
      $('#contact').on('submit', function(){
        $.ajax({
            type: 'POST',
            url: 'unsubscribe.php',
            data: {radio: radio},
            success: function() {
                alert("Success");
            }
        });
      });
});

You should not send the form in a context of an ajax call, so you have to remove the form's action and method.

Because actually, this action is called once the ajax's success callback is reached, so your page is refreshed.

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