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;

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

                url: ajax_url,
                type: 'post',
                dataType: 'json',
                data: {
                    'action'        : 'pincode_search_field',
                    'nonce'         : nonce,
                    'search_query'  : pincode_search_field,
                beforeSend: function() {
            .done(function(response) {
            .fail(function() {
    }, 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;

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

  • 1
    You code is setting a timer so that the keyup event is bound 3 seconds after the page is loaded. If you're trying to have it so that the search isn't performed until 3 seconds after keyup, you need to set the timer on keyup. Better yet you should be debouncing the search. – Jacob Peattie May 27 at 13:45
  • how to do that any help will be appreciated – Raashid Din May 27 at 14:39
  • did of my own. thanks for suggestion – Raashid Din May 27 at 15:03
  • any idea regarding second part of question that is regarding error – Raashid Din May 27 at 15:07

Your Answer

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

Browse other questions tagged or ask your own question.