0

Will anyone help me in this regard. My problem is that when I ajax request WordPress, when I log that response in console it shows error/complete not response.

jQuery(document).ready(function($) {
$(".pincode_search_field").on('keyup', function(event) {
    event.preventDefault();
    var ajax_url = pin_shop.ajax_url;
    var pincode_search_field = $(this).val();
    var nonce  = $(this).data('nonce');

    $.ajax({
        url: ajax_url,
        type: 'POST',
        data: {
            'action'        : 'pincode_search_field',
            'nonce'         : nonce,
            'search_query'  : pincode_search_field,
        },
    })
    .done(function(response) {
        console.log(response.database_result);
        console.log('success');
    })
    .fail(function() {
        console.log("error");
    });
});

});

Here is my PHP 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") ) {
        $result['database_result'] = $wpdb->get_results("SELECT shop_id FROM cs_shop_details WHERE shop_pincode = $pincode");
        $result = json_encode( $result );
        echo $result;
        die();
    }
}

Here is the enqueue script.

add_action( 'wp_enqueue_scripts', function(){
    wp_enqueue_script( 'pin-js', plugins_url() . '/pin-shop/inc/pin.js', array('jquery') );
    wp_localize_script( 'pin-js', 'pin_shop', array(
        'ajax_url' => admin_url('admin-ajax.php'), 
    ) );
});

EDIT: Here is the result in console log. enter image description here

1

As per jQuery documentation, dataType: 'json' is supported. That is the thing that is being returned and parsed by jQuery to your success function. There is more information needed to resolve your issue.

Does pin_shop.ajax_url properly resolve to //site.com/wp-admin/admin-ajax.php? If not, there's your first problem. (To check this, console.log(ajax_url); just before your $.ajax call. I see your enqueue has this.

(Also, did you notice you're not returning your result to the AJAX caller? I put a note of it in the code below.)

Next, you might not be sending your nonce. Check that $(this).data('nonce') resolves to the nonce? (To check this, console.log(nonce); just before your $.ajax call.)

Finally, you may not be resolving your nonce correctly on the server side. To primitively check this, comment out a few lines in your PHP code and see if success/complete is logged to the console, like so:

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

Lastly, there might be an error in your SQL (as in the tablecs_shop_details does not exist or the pincode field does not exist in that table). To check that, comment out $result['database_result'] = ... and set $result=array() so that an empty result will be returned (and make sure $result is echoed).

(Also, I'm new so if any of this helps, and upvote would be appreciated to help me get my score up so that I can comment.)

EDIT: A little debugging, and the problem was learned to be that the PHP function is not echo-ing the json encoded result: add echo $result; just before die().

EDIT 2: In helping to debug the JSON response. First, note the $wpdb->get_results() will return an array. You put that array into the database_result index of the $results array. So, your structure now looks like this...

Array (
    'database_result' => Array (
        [0] => Array(
            "shop_id" => 1
        )
        ... (other results here, indexed sequentially)
    )
)

So, this array is what is being returned to .done(). Access this array accordingly via the response JSON object passed to the related function. I think something like response.database_result[0]["shop_id"] or response.database_result[0].shop_id.

20
  • everything works fine, just showing undefined when i use response.database_result in console – Raashid Din May 27 '20 at 7:28
  • here is the status of code Request URL: localhost/cs/wp-admin/admin-ajax.php Request Method: POST Status Code: 200 OK Remote Address: 127.0.0.1:80 Referrer Policy: no-referrer-when-downgrade – Raashid Din May 27 '20 at 7:31
  • You say "response in console it shows error/complete not response" ... that means the .fail() and .always() blocks of your AJAX are executing. In order for the .done() to execute, the AJAX call must be a success, failing which response.database_result will always be null. What is the value of ajax_url and nonce when logged in the manner I suggested? – Mort 1305 May 27 '20 at 7:32
  • that problem is solved by removing datatype. – Raashid Din May 27 '20 at 7:33
  • 1
    If you echo a json encoded object, AJAX will "guess" that you intended to put dataType: json in your AJAX call. Best practice is to define the dataType (so there is no guessing). Need a bit more info on the response output. What is the javascript you're using? Is it still console.log(response.database_result);? – Mort 1305 May 27 '20 at 7:54

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.