Home Forums Newsletter Plugin Support AJAX Subscription?

Viewing 10 posts - 1 through 10 (of 10 total)
  • Author
    Posts
  • #20598
    vincet
    Participant

    Hello,

    I see in several topics you mention that AJAX subscription is coming. What is the status of this?

    Thanks!

    #20932
    vincet
    Participant

    Anyone?

    #21102
    vincet
    Participant

    Hello? Subscription forms with AJAX…. please

    #21599
    TheFace
    Participant

    Theyve been saying this since 2013 do I doubt they will do anything now! Im still waiting for my reply. Cant seem to stop the STUPID page reload after clicking subscribe. Such a shame because it’d be perfect otherwise.

    #21621
    vincet
    Participant

    I’ve stopped using the plugin because of this. Too bad.

    #25075
    jnz
    Participant

    2013? guess thats plenty of time to learn ajax, right? 🙂

    so here is how it goes. we’ll use the build in wp-ajax functionality to get this rolling. in functions.php you need

    //this populates the ajax url and a security nonce to your js scripts
    //these variables are then available via js_config, expl: js_config.ajax_url will be the url to wp-ajax.php
    wp_localize_script( 'whatever', 'js_config', array(
            'ajax_url'	=> admin_url( 'admin-ajax.php' ),
            'ajax_nonce'	=> wp_create_nonce( 'noncy_nonce' ),
        ));
    
    //this is your subscription form
    //call it inside your template anywhere via <?php echo email_subscribe_container(); ?>
    function email_subscribe_container() {
        echo '<div id="email-subscribe-container"><h4>' . __( 'Subscribe', 'theme_text_domain' ) . '</h4><p>' . __( 'Enter your email address to subscribe to this blog and receive notifications of 
    new posts by email.', 'theme_text_domain' ) . '</p><form id="newsletter_signup">
    <input class="newsletter-email" type="email" name="ne" size="30" placeholder="Email" required />
    <input type="hidden" name="na" value="S">
    <input type="hidden" name="nhr" value="' . get_bloginfo( 'url' ) . '/">
    <input class="newsletter-submit" type="submit" value="Subscribe" />
    </form>
    </div>';
    }
    
    //this is the function, that will get called by ajax
    function jnz_tnp_ajax_subscribe() {
        check_ajax_referer( 'noncy_nonce', 'nonce' );
        $data = urldecode( $_POST['data'] );
        if ( !empty( $data ) ) :
            $data_array = explode( "&", $data );
            $fields = [];
            foreach ( $data_array as $array ) :
                $array = explode( "=", $array );
                $fields[ $array[0] ] = $array[1];
            endforeach;
        endif;
    
        if ( !empty( $fields ) ) :
            global $wpdb;
            $wpdb->insert( $wpdb->prefix . 'newsletter', array(
                    'email'         => $fields['ne'],
                    'status'        => $fields['na'],
                    'http_referer'  => $fields['nhr'],
                )
            );
            $output = array(
                'status'    => 'success',
                'msg'       => __( 'Thank you for your Email. Please check your inbox to confirm your Subscription.', 'theme_text_domain' )
            );
        else :
            $output = array(
                'status'    => 'error',
                'msg'       => __( 'An Error occurred. Please try again later.', 'theme_text_domain' )
            );
        endif;
        wp_send_json( $output );
    }
    add_action( 'wp_ajax_nopriv_ajax_subscribe', 'jnz_tnp_ajax_subscribe' );
    add_action( 'wp_ajax_ajax_subscribe', 'jnz_tnp_ajax_subscribe' );

    //following stuff needs to be placed inside your js script file. place it inside a jQuery ready function.

    var request;
    $("#newsletter_signup").on("submit", function( event ) {
        //abort any previous requests
        if ( request ) {
            request.abort();
        }
        var
            $form = $(this),
            $inputs = $form.find("input, select, button, textarea"),
            serializedData = $form.serialize();
    
        request = $.ajax({
            url: js_config.ajax_url,
            type: 'post',
            data: {
                action: 'ajax_subscribe',
                nonce: js_config.ajax_nonce,
                data: serializedData
            },
            beforeSend: function () {
                //disable the input fields, cause submission will start now
                $inputs.prop( "disabled", true );
            },
            success: function ( response ) {
                //success, we have an answer
                $form.append( '<p class="newsletter-' + response.status + '">' + response.msg + '</p>' );
                //console.log("success", response );
            },
            error: function ( response, textStatus, errorThrown ) {
                //failllll
                //console.log("error", response, textStatus, errorThrown );
            },
            complete: function() {
                //reenable the input fields again
                $inputs.prop( "disabled", false );
            }
        });
    
        event.preventDefault();
    });

    ##OOOPS. sorry for the falsy charracters. maybe an admin knows how to fix this crap..
    otherwise i reccomend search&replace..

    • This reply was modified 6 years, 3 months ago by jnz.
    #25092
    jnz
    Participant

    if found an issue with my code. the email address might not be valid, the javascript pre-validation isn’t complete, so i now also check the email on the serverside (email@example would work, but thats not valid, email@example.tld is valid..)

    new code for inside the jnz_tnp_ajax_subscribe() function:

    function jnz_tnp_ajax_subscribe() {
        //check the nonce
        check_ajax_referer( 'pn', 'nonce' );
        //grab the submitted $_POST data
        $data = urldecode( $_POST['data'] );
        if ( !empty( $data ) ) :
            $data_array = explode( "&", $data );
            $fields = [];
            foreach ( $data_array as $array ) :
                $array = explode( "=", $array );
                $fields[ $array[0] ] = $array[1];
            endforeach;
        endif;
    
        if ( !empty( $fields ) ) :
             //validate the email
             if ( filter_var( $fields['ne'], FILTER_VALIDATE_EMAIL ) ) :
                //write to db
                global $wpdb;
                $wpdb->insert( $wpdb->prefix . 'newsletter', array(
                        'email'         => $fields['ne'],
                        'status'        => $fields['na'],
                        'http_referer'  => $fields['nhr'],
                    )
                );
                //success response
                $output = array(
                    'status'    => 'success',
                    'msg'       => __( 'Thank you for your Email. Please check your inbox to confirm your Subscription.', 'blank' )
                );
             else :
                 //email invalid response
                 $output = array(
                     'status'    => 'error',
                     'msg'       => __( 'The Email address is invalid.', 'blank' )
                 );
             endif;
        else :
            //error response ( $fields array is empty )
            $output = array(
                'status'    => 'error',
                'msg'       => __( 'An Error occurred. Please try again later.', 'blank' )
            );
        endif;
    
        //ajax response
        wp_send_json( $output );
    }
    //add own functions to wp-ajax
    add_action( 'wp_ajax_nopriv_ajax_subscribe', 'jnz_tnp_ajax_subscribe' );
    add_action( 'wp_ajax_ajax_subscribe', 'jnz_tnp_ajax_subscribe' );
    #27057
    jnz
    Participant

    so one more time step by step.
    first of some stuff that needs to be in functions.php its two things: javascript variables (like nonce and path to wp-ajax) and our function that invokes the signup. and we need some javascript (jquery, to be specific)
    this is the best solution, since the previous version did not send out the double opt-in emails.. this one does..

    for javascript variables:

    function blank_scripts() {
        wp_localize_script( 'requireJS', 'js_config', array(
            'ajax_url'	=> admin_url( 'admin-ajax.php' ),
            'ajax_nonce'	=> wp_create_nonce( 'ajax-nonce' ),
        ));
    }
    add_action( 'wp_enqueue_scripts', 'blank_scripts' );

    and the function for signup:

    function jnz_tnp_ajax_subscribe() {
        check_ajax_referer( 'ajax-nonce', 'nonce' );
        $data = urldecode( $_POST['data'] );
        if ( !empty( $data ) ) :
            $data_array = explode( "&", $data );
            $fields = [];
            foreach ( $data_array as $array ) :
                $array = explode( "=", $array );
                $fields[ $array[0] ] = $array[1];
            endforeach;
        endif;
    
        if ( !empty( $fields ) ) :
             if ( filter_var( $fields['ne'], FILTER_VALIDATE_EMAIL ) ) :
                global $wpdb;
    
                 //check if the email is already in the database
                 $exists = $wpdb->get_var(
                     $wpdb->prepare(
                         "SELECT email FROM " . $wpdb->prefix . "newsletter
                        WHERE email = %s",
                         $fields['ne']
                     )
                 );
    
                 if ( ! $exists ) {
                     NewsletterSubscription::instance()->subscribe();
                     $output = array(
                         'status'    => 'success',
                         'msg'       => __( 'Thank you for your Email. Please check your inbox to confirm your subscription.', 'theme_text_domain' )
                     );
                 } else {
                     //email is already in the database
                     $output = array(
                         'status'    => 'error',
                         'msg'       => __( 'Your Email is already in our system. Please check your inbox, to confirm your subscription.', 'theme_text_domain' )
                     );
                 }
    
             else :
                 $output = array(
                     'status'    => 'error',
                     'msg'       => __( 'The Email address is invalid.', 'theme_text_domain' )
                 );
             endif;
        else :
            $output = array(
                'status'    => 'error',
                'msg'       => __( 'An Error occurred. Please try again later.', 'theme_text_domain' )
            );
        endif;
        wp_send_json( $output );
    }
    add_action( 'wp_ajax_nopriv_ajax_subscribe', 'jnz_tnp_ajax_subscribe' );
    add_action( 'wp_ajax_ajax_subscribe', 'jnz_tnp_ajax_subscribe' );

    and here is the javascript: (post it inside jQuery ready..)

    var request;
            $("#YOUR FORM THAT WILL BE SUBMITTED").on("submit", function( event ) {
                if ( request ) {
                    request.abort();
                }
                var
                    $form = $(this),
                    $inputs = $form.find("input, select, button, textarea"),
                    serializedData = $form.serialize();
    
                request = $.ajax({
                    url: js_config.ajax_url,
                    type: 'post',
                    data: {
                        action: 'ajax_subscribe',
                        nonce: js_config.ajax_nonce,
                        ne: $form.find('.newsletter-email').val(), //THIS IS IMPORTANT TO SUBMIT!! ITS REQUIRED BY THE subscribe() METHOD
                        data: serializedData
                    },
                    beforeSend: function () {
    //disable all field
                        $inputs.prop( "disabled", true );
                    },
                    success: function ( response ) {
    //we have an answer. it will be placed right after our form
                        var text = $( '<p class="newsletter-' + response.status + '">' + response.msg + '</p>' ).hide();
                        $form.after( text ).next().slideDown();
                    },
                    complete: function() {
    //we are done, reenable all fields
                        $inputs.prop( "disabled", false );
                    }
                });
    
                event.preventDefault();
            });
    • This reply was modified 6 years ago by jnz.
    • This reply was modified 6 years ago by jnz.
    #28371
    Claire39
    Participant

    Hi jnz,
    I’m looking for a solution to have a “You have successfully subscribed to the newsletter” message in the same page, and I found your contribution, thank you !
    But… can you help me to find what’s wrong ?
    I used your last response exactly, changing ‘$(“#YOUR FORM THAT WILL BE SUBMITTED”).on(“submit”, function( event ) {‘ with the id of my form,

    and I inserted manually this form in my HTML:

    <form id="lechatquipete">			
    	<input class="newsletter-email" type="email" name="ne" size="30" placeholder="Email" required />
    	<input type="hidden" name="na" value="S">
    	<input type="hidden" name="nhr" value="http://mydomain.com/">
    	<input class="newsletter-submit" type="submit" value="Subscribe" />
    </form>

    …exactly the form you suggested to put in the function.php file.

    So, when I enter a new email address, the same page is re-loaded, with an awful url :
    http://mydomain.com/?ne=email%40adress.com&na=S&nhr=http%3A%2F%2Fmydomain.com%2F

    No message in a new paragraph, and no new subscription in the list

    What do I wrong ?
    Thank you for answer, and merry Christmas !

    #30977
    johnpaul86
    Participant

    Here you find the addon plugin which enables the ajax functionality for your ‘thenewsletterplugin’.

Viewing 10 posts - 1 through 10 (of 10 total)
  • You must be logged in to reply to this topic.