Find answers, ask questions, and connect with our
community around the world.

Activity Forums Web Design WordPress Send form via XMLHttpRequest

  • Send form via XMLHttpRequest

    updated 2 weeks, 5 days ago 0 Member · 1 Post
  • Deborah

    Member
    October 26, 2019 at 7:33 pm

    I have a simple contact form on a page I’m building. How can I make it working? I have this code in functions.php: add_action(‘wp_head’, ‘myplugin_ajaxurl’); function myplugin_ajaxurl() { echo ‘ var ajaxurl = “‘ . admin_url(‘admin-ajax.php’) . ‘”; ‘; } //form send add_action(‘wp_ajax_mail_form’, ‘mail_form’); add_action(‘wp_ajax_nopriv_mail_form’, ‘mail_form’); function mail_form() { $data = $_POST[‘data’]; if(isset($_POST[‘data’])) { parse_str($_POST[‘data’], $searcharray); } $body = ”; foreach ($searcharray as $key => $value) { $body .= $key . “: ” . $value . “”; } $to = ‘example-mail@mail.com’; $subject = ‘form’; $headers = ‘Content-type:text/html;charset=UTF-8’; wp_mail($to, $subject, $body, $headers); die(); } ​ And in my page-contact.php I have this request:` const formE = document.querySelector(“form”) formE.addEventListener(“submit”, submitForm) function submitForm(e) { e.preventDefault() var request = new XMLHttpRequest(); const form = document.querySelector(“#contact-submit-form”); const fData = new URLSearchParams(new FormData(form)).toString() var action = “mail_form” request.open(‘POST’, ”, true); request.setRequestHeader(‘Content-Type’, ‘multipart/form-data; charset=UTF-8’); request.onload = function () { if (request.status >= 200 && request.status < 400) { var result = request.responseText; console.log(action=mail_form&&{fData}); } }; request.send(fData); } ​ Of course it's not working, I get no output or ``` admin-ajax.php 400 (Bad Request)``` in the best try. So how can i make this request using only JS (No jquery please). - by hq overview icelandico - -

Reply to: Deborah
Your information:

Cancel
Original Post
0 of 0 posts June 2018
Now