Submitting a subscribe form to an external service via AJAX
When a subscription form posts directly to an external service, the browser redirects the user away from the site on submit. Intercepting the form with AJAX and forwarding the data server-side via cURL lets you show a confirmation message inline without navigating away.
Problem: When using a subscribe script hosted on an external service, after subscribing users are redirected to that external page — we want to keep them on the site.
Solution: Handle the submission via AJAX. The original form looks like this:
<form id="subscribeForm" method="post" action="http://cl.exct.net/subscribe.aspx?lid=1234567" name="subscribeForm">
<input type="hidden" name="thx" value="http://example.com/thank-you.jsp">
<input type="hidden" name="err" value="http://example.com/error.jsp">
<input type="hidden" name="MID" value="12345678">
</form>
Step 1. Update the form — remove the action attribute and add a nonce:
<form id="subscribeForm" method="post" name="subscribeForm">
<input type="hidden" name="thx" value="http://example.com/thank-you.jsp">
<input type="hidden" name="err" value="http://example.com/error.jsp">
<input type="hidden" name="MID" value="12345678">
<script>var nonce = '<?php echo wp_create_nonce( "send_form_nonce" ); ?>';</script>
<div id="response"></div>
</form>
Step 2. Add the AJAX handler script:
( function( $ ) {
var form = $( '#subscribeForm' );
form.on( 'submit', function( e ) {
e.preventDefault();
$.ajax( {
url: ajax.url,
type: 'post',
data: {
action: 'sendform',
query: form.serialize(),
nonce_code: nonce,
},
success: function( response ) {
$( '#response' ).html( response );
},
} );
} );
} )( jQuery );
Step 3. Set up the back-end handler in functions.php using cURL:
add_action( 'wp_ajax_sendform', 'send_subscribe_form' );
add_action( 'wp_ajax_nopriv_sendform', 'send_subscribe_form' );
function send_subscribe_form() {
check_ajax_referer( 'send_form_nonce', 'nonce_code' );
$url = 'http://cl.exct.net/subscribe.aspx?lid=1234567';
$params = $_POST['query'];
$ch = curl_init();
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec( $ch );
curl_close( $ch );
$message = '';
if ( strpos( $result, 'thank-you.jsp' ) !== false ) {
$message = '<p class="success">' . __( 'Thank you for subscribing!', 'domain' ) . '</p>';
} elseif ( strpos( $result, 'error.jsp' ) !== false ) {
$message = '<p class="error">' . __( 'Please check your details and try again.', 'domain' ) . '</p>';
}
echo $message;
wp_die();
}
NOTE: Always validate and whitelist POST fields before forwarding them to an external URL. In this example check_ajax_referer() guards against CSRF, but in production parse $_POST['query'] and pass only the expected field names to the cURL request.