Black Friday: 79% off every plugin Shop the sale →

Newsletter Sign-up AJAX

SmartCouponX does not render a newsletter form. Connect your own form to the smartcouponx_newsletter_subscribe AJAX action and the plugin issues the newsletter coupon, stores the subscriber and emails the code.

Contract#

ItemValue
URLadmin-ajax.php (admin_url('admin-ajax.php'))
MethodPOST
actionsmartcouponx_newsletter_subscribe
emailThe subscriber’s email address
nonceA nonce created with wp_create_nonce('smartcouponx_nonce')
Who may call itLogged-in users and visitors (wp_ajax and wp_ajax_nopriv)

Enable Newsletter Coupons under WooCommerce > SmartCouponX > Triggers first, otherwise the action answers with HTTP 403.

Responses#

HTTPsuccessdataMeaning
200true{ "message": "Thank you for subscribing! Check your email for your reward coupon." }Coupon created and emailed
200false"Invalid email address."The address did not validate
200false"Email already subscribed."This address was rewarded before
200false"Failed to create coupon."Coupon creation failed; check the WooCommerce log
403false"Newsletter subscriptions are not available."The trigger is disabled
429false"Too many requests. Please try again later."The per-IP daily limit was reached
403–-1Missing or invalid nonce

Example#

Enqueue the nonce with your form script:

add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_script( 'my-newsletter', get_stylesheet_directory_uri() . '/js/newsletter.js', [ 'jquery' ], '1.0', true );
    wp_localize_script( 'my-newsletter', 'myNewsletter', [
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'smartcouponx_nonce' ),
    ] );
} );

Then post the form:

jQuery( '#my-newsletter-form' ).on( 'submit', function ( e ) {
    e.preventDefault();
    jQuery.post( myNewsletter.ajaxUrl, {
        action: 'smartcouponx_newsletter_subscribe',
        email:  jQuery( '#my-newsletter-email' ).val(),
        nonce:  myNewsletter.nonce
    } ).done( function ( response ) {
        var text = response.data && response.data.message ? response.data.message : response.data;
        jQuery( '#my-newsletter-result' ).text( text );
    } ).fail( function ( xhr ) {
        var text = xhr.responseJSON && xhr.responseJSON.data ? xhr.responseJSON.data : 'Please try again later.';
        jQuery( '#my-newsletter-result' ).text( text );
    } );
} );

If your mailing list lives in another service, send the address there first and call this action afterwards so the coupon only goes to confirmed subscribers.

Was this article helpful?