Home > Software engineering >  Doesn't send wp_mail() message with AJAX
Doesn't send wp_mail() message with AJAX

Time:01-08

I have a form on my page. I am sending data without plugins, using wp_mail(). The submit code is in function.php and I am pasting the form as a shortcode on the page. The form works, submits data. The problem now is that I want to send data using AJAX so that the page doesn't reload. I wrote the code, but it doesn't work and the page still reloads. How can i do this?

//function.php

function display_contact_form()
{
            $mail    = get_option('admin_email');
            $subject = 'New message from ' . $full_name;
            $message = $message . ' - The email address of the customer is: ' . $mail;

            wp_mail($mail, $subject, $message);
?>

    <form id="contact-form" action="<?php echo esc_url(get_permalink()); ?>" method="post">
        <input type="hidden" name="contact_form">
        <div >
            <input type="text" id="full-name" name="full_name" placeholder="Name">
        </div>
        <div >
            <input type="text" id="email" name="email" placeholder="Email">
        </div>
        <div >
            <textarea id="message" name="message" placeholder="Write something..."></textarea>
        </div>
        <button type="submit" id="contact-form-submit">
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path fill-rule="evenodd" clip-rule="evenodd" d="M1.81818 4.85279L9.39603 11.5887C9.74047 11.8948 10.2595 11.8948 10.604 11.5887L18.1818 4.85279V15.4547C18.1818 15.9567 17.7748 16.3637 17.2727 16.3637H2.72727C2.22519 16.3637 1.81818 15.9567 1.81818 15.4547V4.85279ZM3.1865 3.63647H16.8134L9.99995 9.69288L3.1865 3.63647Z" fill="white" />
            </svg>
            Submit Message
        </button>
    </form>
<?php

}

//script.js

$("#contact-form-submit").click(function() {
  $.ajax({
    type: "POST",
    dataType: "html",
    url: "/wp-admin/admin-ajax.php",
    data: {
      action: "display_contact_form"
    },
    success: function(response) {
      console.log("success")
    }
  });
});

CodePudding user response:

The event handler will execute your code, and then go on to do what it would normally do, unless you tell it otherwise. A submit button will submit the data and load a new page unless you tell it not to.

You need to call .preventDefault() in your event handler, or return false to prevent the usual behaviour.

In your code then:

//script.js

$("#contact-form-submit").click(function(event) {     // pass the event object to the handler
  event.preventDefault();
  $.ajax({
    type: "POST",
    dataType: "html",
    url: "/wp-admin/admin-ajax.php",
    data: {
      action: "display_contact_form"
    },
    success: function(response) {
      console.log("success")
    }
  });
});

MDN Reference

  • Related