2

So there's function in wordpress to update a named option/value pair to the options database table: <?php update_option( $option, $new_value ); ?>. And what I'm trying to do implement this function in javascript so when you hit the bottom of the page an option would update. I am using this script to check when you hit bottom of the page:

$(window).scroll(function () {
   if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
      /***update options***/
   }
});

So my question is how to implement update_option function into javascript.

  • 2
    Use ajax. Have you tried that? – fuxia Jun 4 '13 at 10:24
1

JavaScript

$(window).scroll(function () {
    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        /***update options***/
        $.ajax({
            type:   'POST',
            url:    'http://www.example.com/wp-admin/admin-ajax.php',
            data:   {
                action    : 'hit-bottom',
                option    : $option, // your option variable
                new_value : $new_value // your new value variable
            },
            dataType: 'json'
        }).done(function( json ) {
            alert( "Ajax call succeeded, let's see what the response was." );
            if( json.success ) {
                alert( "Function executed successfully and returned: " + json.message );
            } else if( !json.success ) {
                alert( "Function failed and returned: " + json.message );
            }
        }).fail(function() {
            alert( "The Ajax call itself failed." );
        }).always(function() {
            alert( "This message is always displayed, whether the call failed or succeeded." );
        });
    }
});

functions.php

/* hit bottom of screen event  */
add_action( 'wp_ajax_hit-bottom', 'wpse_hit_bottom' );
add_action( 'wp_ajax_nopriv_hit-bottom', 'wpse_hit_bottom' );
function wpse_hit_bottom() {
    $option = $_POST['option'];
    $new_value = $_POST['new_value'];

    if( !isset( $option ) || $option == '' || !isset( $new_value ) || $new_value = '' ) {
        die(
            json_encode(
                array(
                    'success' => false,
                    'message' => 'Missing required information.'
                )
            )
        );
    }

    update_option( $option, $new_value );
    die(
        json_encode(
            array(
                'success' => true,
                'message' => 'Database updated successfully.'
            )
        )
    );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.