Home > Blockchain >  Getting 400 bad request while trying to use ajax in wordpress
Getting 400 bad request while trying to use ajax in wordpress

Time:11-18

I am trying to get the response from wordpress ajax. but Getting 400 error. Can not find out where is the issue. I have tried many times but could not resolve. jQuery version 3.6. and filter.js file is working perfectly. Please help me.

function.php

add_action( 'init', 'my_script_enqueuer' );

function my_script_enqueuer() {
    wp_register_script( "filter_script", get_template_directory_uri() . '/assets/js/filter.js', array('jquery') );
    wp_localize_script( 'filter_script', 'filterAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        
    wp_enqueue_script( 'filter_script' );

}


add_action("wp_ajax_publication_filter_function]", "publication_filter_function");
add_action("wp_ajax_nopriv_publication_filter_function", "publication_filter_function");

function publication_filter_function(){
    echo "Response hello";
}

filter.js

jQuery(document).ready( function() {
    // Get filter value 
    jQuery('.publication-filter').on('change', function(e){
        e.preventDefault();
        var filter_value = this.value;
        var nonce_val = jQuery('.filter_ajax_nonce').val();
        
        jQuery.ajax({
            type : "POST",
            url : filterAjax.ajaxurl,
            data : {
                action: "publication_filter_function", 
                filter_value : filter_value, 
                nonce: nonce_val
            },
            success: function(response) {
                if(response.type == "success") {
                console.log("Hello");
                }
                else {
                console.log("Not hello");
                }
            },
            error : function(error){ console.log(error) }
        });
    })
});

response enter image description here

CodePudding user response:

You need to change this line:

add_action("wp_ajax_publication_filter_function", "publication_filter_function");

I think you have added the ] bracket by mistake to the ajax hook that's why the ajax call is not working.

  • Related