Support » Developing with WordPress » WordPress form handling with admin-ajax

  • Resolved ace0930

    (@ace0930)


    There is the official documentation of the form handling with admin_post_{$action}

    https://developer.wordpress.org/reference/hooks/admin_post_action/

    But I don’t know why there is none about admin_ajax_{$action} which I also couldn’t find a really relevant and detailed explanation when I google.

    Assume I have the below minimal example code:

    
    <form action="<?php echo admin_url( 'admin-ajax.php' ) ?> " method="post">
       <input type="hidden" name="action" value="capture_form">
       <input id="fname" placeholder="First Name" type="text" name="fname">
       <input id="lname" placeholder="Last Name" type="text" name="lname">
       <input type="submit" value="Submit">
    </form>
    

    With this in the functions.php:

    
    add_action( 'admin_ajax_capture_form', 'capture_form' );
    
    function capture_form() {
       // Do something
    }
    
    wp_enqueue_script(
       'example',
       'https://www.example.com/script.js',
       array(),
       null,
       true
    );
    

    And JavaScript that uses fetch():

    
    const firstName =  document.getElementById('fname').value,
       lastName = document.getElementById('lname').value,
       data = { firstName: firstName, lastName: lastName };
    
    fetch('https://www.example.com/form-handling.php', {
       method: 'POST',
       headers: {
          'Content-Type': 'application/json',
       },
       body: JSON.stringify(data),
    });
    

    My question now is:
    1) How do I send the data to the PHP file ( https://www.example.com/form-handling.php ) that would be used to handle the data? For the old school method, I think it should be something like the below but I don’t know how to send it with fetch() :

    
    const request = new XMLHttpRequest();
    request.send(data);
    

    2) How do I get the data that is sent by fetch() and store it in the variables in the PHP file

    ( https://www.example.com/form-handling.php ) ?

    
    $first_name = // How to get the <code>const firstName</code> from the JavaScript?
    $last_name = // How to get the <code>const lastName</code> from the JavaScript?
    
Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter ace0930

    (@ace0930)

    Update: it now returns <empty string> in the console with the below code:

    
    <form id="contact-form" method="post">
       <input type="hidden" name="action" value="form_handling">
       <input id="fname" placeholder="First Name" type="text" name="fname">
       <input id="lname" placeholder="Last Name" type="text" name="lname">
       <input id="email" placeholder="Email Address" type="email" name="email">
       <input id="phone" placeholder="Phone Number" type="tel" name="phone">
       <textarea id="message" placeholder="Your Message..." name="message" rows="3"></textarea>
       <input id="submit-form" type="submit" value="Submit"> 
    </form>
    

    With this in the functions.php:

    
    function form_handling() {
       $first_name = sanitize_text_field( $_POST['fname'] );
       $last_name = sanitize_text_field( $_POST['lname'] );
       $email = sanitize_email( $_POST['email'] );
       $phone = sanitize_text_field( $_POST['phone'] );
       $message = sanitize_textarea_field( $_POST['message'] );
       $mail = 'user@test.com';
       $subject = 'New Submission';
       $data = $first_name . ' ' . $last_name . ' ' . $email . ' ' . $phone . ' ' . $message;
       $headers = 'From: Company <local@test.com>';
    
       wp_mail( $mail, $subject, $data, $headers );
    
       wp_die();
    }
    
    wp_enqueue_script(
       'example',
       'https://local.test/script.js',
       array(),
       null,
       true
    );
    

    And JavaScript that uses fetch():

    
    const contactForm = document.querySelector('#contact-form'),
       btnSubmit = document.querySelector('#submit-form'),
       ajaxData = new FormData(contactForm);
    
    btnSubmit.addEventListener('click', function(e) {
       e.preventDefault();
    
       fetch('https://local.test/wp-admin/admin-ajax.php', {
          method: 'POST',
          body: ajaxData
       }).then( res => res.text() )
       .then( data => {
          console.log( data );
       }).catch( err => {
          console.log(err);
       });
    })
    
    Thread Starter ace0930

    (@ace0930)

    .then( data => { console.log(data) } is the message returns from the server and not the message sent to the server.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.