/* global woolist, jQuery */ ( function ( $ ) { 'use strict'; $( document ).on( 'submit', '#woolist-newsletter-form', function ( e ) { e.preventDefault(); var $form = $( this ); var $wrap = $form.closest( '.woolist-newsletter-wrap' ); var $btn = $form.find( '.woolist-submit-btn' ); var $email = $form.find( '[name="woolist_email"]' ); var $resp = $wrap.find( '.woolist-response' ); // Clear previous response state. $resp.hide().removeClass( 'woolist-success woolist-error' ).html( '' ); var email = $email.val().trim(); if ( ! email ) { showResponse( $resp, woolist.i18n.error, false ); return; } // Loading state. var originalLabel = $btn.text(); $btn.prop( 'disabled', true ).text( woolist.i18n.subscribing ); $.ajax( { url: woolist.ajaxurl, method: 'POST', data: { action: 'woolist_newsletter_submit', nonce: woolist.nonce, woolist_email: email, }, } ) .done( function ( response ) { if ( response.success && response.data && response.data.message ) { // Hide the form, show the success message. $form.slideUp( 200 ); showResponse( $resp, response.data.message, true ); } else { var msg = ( response.data && response.data.message ) ? response.data.message : woolist.i18n.error; showResponse( $resp, msg, false ); $btn.prop( 'disabled', false ).text( originalLabel ); } } ) .fail( function () { showResponse( $resp, woolist.i18n.error, false ); $btn.prop( 'disabled', false ).text( originalLabel ); } ); } ); /** * Display a response message in the response container. * * @param {jQuery} $el The response element. * @param {string} message HTML or text message to display. * @param {boolean} success Whether this is a success message. */ function showResponse( $el, message, success ) { $el .addClass( success ? 'woolist-success' : 'woolist-error' ) .html( message ) .slideDown( 200 ); } } )( jQuery );