admin管理员组

文章数量:1335895

Will someone please tell me why the timer isn't working. Here is my jQuery code.

jQuery(document).ready(function($) {
    var timer = '';
    var ajax_url = pin_shop.ajax_url;
    clearTimeout(timer);

    timer = setTimeout(function(){
        $(".pincode_search_field").on('keyup', function() {
            var pincode_search_field = $(this).val();
            var nonce  = $(this).data('nonce');

            $.ajax({
                url: ajax_url,
                type: 'post',
                dataType: 'json',
                data: {
                    'action'        : 'pincode_search_field',
                    'nonce'         : nonce,
                    'search_query'  : pincode_search_field,
                },
                beforeSend: function() {
                    console.log('loading');
                }
            })
            .done(function(response) {
                console.log(response.database_result[0].shop_name);
            })
            .fail(function() {
                console.log('error');
            });
        });
    }, 3000 );
});

It sometimes execute code when i press key (instantly) and sometimes doesn't execute code at all. Where I am doing it wrong.

Also, my code response.database_result[0].shop_name shows Uncaught TypeError: Cannot read property 'shop_name' of undefined. Once the code executes it first logs this error and then shows the response from ajax in console.

Here is the backend code which handles ajax code.

add_action( "wp_ajax_pincode_search_field", 'pincode_search_field' );
add_action( "wp_ajax_nopriv_pincode_search_field", 'pincode_search_field' );

function pincode_search_field() {
    global $wpdb;
    $pincode = $_REQUEST['search_query'];
    if ( wp_verify_nonce( $_REQUEST['nonce'], "pin_shop_nonce") ) {
        $sql_query = $wpdb->get_results("SELECT shop_name FROM cs_shop_details WHERE shop_pincode = $pincode");
        $result['database_result'] = $sql_query;
        $result = json_encode( $result );
        echo $result;
        die();
    }
}

Anyone with any suggestion how to fix this. Any help will be appreciated.

本文标签: plugin developmentsetTimeout not working in jquery