How send subscribe form on outer subscribe resource use AJAX

Submitting a subscribe form to an external service via AJAX

When a subscription form posts directly to an external service, the browser takes the user away from the site on submit. Intercepting the form with AJAX and forwarding the data from the server lets you show a confirmation message inline without navigating away.

Problem: When using a subscribe form hosted by an external service, users are redirected to that service’s page after subscribing. We want to keep them on the site.

Solution: Handle the submission via AJAX and send the data to the service from WordPress. The original form looks like this:

<form id="subscribeForm" method="post" action="https://cl.exct.net/subscribe.aspx?lid=1234567" name="subscribeForm">
    <input type="email" name="Email Address" required>
    <input type="hidden" name="thx" value="https://example.com/thank-you.jsp">
    <input type="hidden" name="err" value="https://example.com/error.jsp">
    <input type="hidden" name="MID" value="12345678">
</form>

Step 1. Remove the action attribute

The form now submits to our own handler, and a container is added for the response message:

<form id="subscribeForm" method="post" name="subscribeForm">
    <input type="email" name="Email Address" required>
    <input type="hidden" name="thx" value="https://example.com/thank-you.jsp">
    <input type="hidden" name="err" value="https://example.com/error.jsp">
    <input type="hidden" name="MID" value="12345678">
    <button type="submit">Subscribe</button>
    <div id="response"></div>
</form>

Step 2. Pass the AJAX URL and a nonce to the script

add_action( 'wp_enqueue_scripts', 'helloadmin_subscribe_script' );
function helloadmin_subscribe_script() {
    wp_enqueue_script( 'subscribe', get_template_directory_uri() . '/js/subscribe.js', array( 'jquery' ), null, true );
    wp_localize_script( 'subscribe', 'subscribeData', array(
        'url'   => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce( 'send_form_nonce' ),
    ) );
}

Step 3. Send the form with AJAX

In js/subscribe.js:

( function( $ ) {
    var form = $( '#subscribeForm' );

    form.on( 'submit', function( e ) {
        e.preventDefault();

        $.post( subscribeData.url, {
            action:     'sendform',
            query:      form.serialize(),
            nonce_code: subscribeData.nonce
        }, function( response ) {
            $( '#response' ).html( response );
        } );
    } );
} )( jQuery );

Step 4. Forward the data to the service

In functions.php, accept only the fields the service expects and send them with wp_remote_post():

add_action( 'wp_ajax_sendform',        'helloadmin_send_subscribe_form' );
add_action( 'wp_ajax_nopriv_sendform', 'helloadmin_send_subscribe_form' );
function helloadmin_send_subscribe_form() {
    check_ajax_referer( 'send_form_nonce', 'nonce_code' );

    parse_str( wp_unslash( $_POST['query'] ?? '' ), $fields );

    $email = sanitize_email( $fields['Email_Address'] ?? '' ); // PHP turns spaces in names into "_".

    if ( ! is_email( $email ) ) {
        echo '<p class="error">' . esc_html__( 'Please enter a valid email address.', 'domain' ) . '</p>';
        wp_die();
    }

    $response = wp_remote_post( 'https://cl.exct.net/subscribe.aspx?lid=1234567', array(
        'timeout'     => 15,
        'redirection' => 0, // We only need to know where the service wants to send the user.
        'body'        => array(
            'Email Address' => $email,
            'thx'           => 'https://example.com/thank-you.jsp',
            'err'           => 'https://example.com/error.jsp',
            'MID'           => '12345678',
        ),
    ) );

    $location = wp_remote_retrieve_header( $response, 'location' );
    $body     = wp_remote_retrieve_body( $response );

    if ( false !== strpos( $location . $body, 'thank-you.jsp' ) ) {
        echo '<p class="success">' . esc_html__( 'Thank you for subscribing!', 'domain' ) . '</p>';
    } else {
        echo '<p class="error">' . esc_html__( 'Please check your details and try again.', 'domain' ) . '</p>';
    }

    wp_die();
}

Why not forward the raw form data

The browser can send anything in query. If the handler passed it to the service as it is, anyone could use your server to send arbitrary data to that URL. Here the hidden values are set on the server, and only the email address comes from the visitor, after validation. check_ajax_referer() protects the handler against requests from other sites.

The service tells us the result through the “thank you” or “error” URL it redirects to. With 'redirection' => 0, wp_remote_post() does not follow the redirect, and we read the target from the Location header.