Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting 400 bad request while trying to use ajax in wordpress

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading