ajax sending 400 bad request error in wordpress

Hi everyone i am trying to use ajax in wordpress and got stuck in something. My code is giving me an error in console as

    jquery-3.3.1.js:9600 GET http://localhost/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)
send @ jquery-3.3.1.js:9600
ajax @ jquery-3.3.1.js:9206
(anonymous) @ main.js?ver=1:27
dispatch @ jquery-3.3.1.js:5183
elemData.handle @ jquery-3.3.1.js:4991

I looked into the source and it is showing me the error on this line

xhr.send( options.hasContent && options.data || null );

This is my jquery

$('#retrieve_users').click(function() {

            type: "GET",
            url: scriptData.ajaxurl,
            action : 'retrieveUsersData',
            dataType: "html",   //expect html to be returned                
            success: function(response)

This is my php code in functions.php file

function retrieveUsersData(){

echo "ajax responding";

add_action('wp_ajax_nopriv_retrieveUsersData', 'retrieveUsersData');

and this is my html

<button id="retrieve_users">Watch Users</button>
                <div id="users_data"></div>

Please help!! I didnt know how to import jquery src link in wordpress using wp_enque_scripts so i pasted the with jquery src directly in html. I hope its not creating problem

Please help.. i would really appreciate it. Thank you


Change your code to use POST and in the body of the request use the action key :

            url: scriptData.ajaxurl,
            type: "POST",
            dataType: 'html',
            data: {
                action: 'retrieveUsersData'


Also you should use wp_die() in the function to prevent the 0 to be echoed.

function retrieveUsersData(){
    echo "ajax responding";

Leave a Reply

Your email address will not be published. Required fields are marked *