questions

WordPress ajax call getting 400 error in custom plugin

Rate this post

I am creating a custom plugin in WordPress admin and I want to use ajax call inside plugin. My plugin has different folders. I have written following scripts but its giving me 400 (bad request) error. I use latest wordpress.

I tried to get answer from other post but not able to find what is the issue here. When I am moving the code to function.php everything working but I dont want to use function.php.

The code below has been written in single php file ( say dahboard.php)

    <?php
add_action( 'admin_footer', 'ajax_without_file' );
function ajax_without_file() { ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {
        var dataVariable = {
            'action': 'my_action_without_file', // your action name
            'variable_name': "Some value" // some additional data to send
        };

        jQuery.ajax({
            url: ajaxurl, // this will point to admin-ajax.php
            type: 'POST',
            data: dataVariable, 
            success: function (response) {
                console.log(response);
            }
        });
    });
    </script> 
    <?php
}


add_action ('wp_ajax_my_action_without_file' , 'my_action_without_file');
add_action('wp_ajax_nopriv_my_action_without_file','my_action_without_file');

function my_action_without_file(){
    echo json_encode($_POST);
    wp_die();
}
?>

 

✔️Solution:

Try this. I’ve changed “ajaxurl” to <?php echo admin_url( 'admin-ajax.php' ); ?>

<?php
add_action( 'admin_footer', 'ajax_without_file' );
function ajax_without_file() { ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {
        var dataVariable = {
            'action': 'my_action_without_file', // your action name
            'variable_name': "Some value" // some additional data to send
        };

        jQuery.ajax({
            url: <?php echo admin_url( 'admin-ajax.php' ); ?>, // this will point to admin-ajax.php
            type: 'POST',
            data: dataVariable, 
            success: function (response) {
                console.log(response);
            }
        });
    });
    </script> 
    <?php
}


add_action ('wp_ajax_my_action_without_file' , 'my_action_without_file');
add_action('wp_ajax_nopriv_my_action_without_file','my_action_without_file');

function my_action_without_file(){
    echo json_encode($_POST);
    wp_die();
}
?>

Leave a Reply

Your email address will not be published.

Back to top button