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#
| Item | Value |
|---|---|
| URL | admin-ajax.php (admin_url('admin-ajax.php')) |
| Method | POST |
action | smartcouponx_newsletter_subscribe |
email | The subscriber’s email address |
nonce | A nonce created with wp_create_nonce('smartcouponx_nonce') |
| Who may call it | Logged-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#
| HTTP | success | data | Meaning |
|---|---|---|---|
| 200 | true | { "message": "Thank you for subscribing! Check your email for your reward coupon." } | Coupon created and emailed |
| 200 | false | "Invalid email address." | The address did not validate |
| 200 | false | "Email already subscribed." | This address was rewarded before |
| 200 | false | "Failed to create coupon." | Coupon creation failed; check the WooCommerce log |
| 403 | false | "Newsletter subscriptions are not available." | The trigger is disabled |
| 429 | false | "Too many requests. Please try again later." | The per-IP daily limit was reached |
| 403 | – | -1 | Missing 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?
Tell us what was missing
