0

I'm facing an issue and I can't get the reason, I tried to print the variables and check for typo errors, But couldn't find any.

I send an Ajax request to admin-ajax:

function update_order() {
    var orderdata = {
        action: 'update_order_ajax',
        data: 'test'
    };

    jQuery.ajax({
        type: 'POST',
        beforeSend: function (jqXHR) {
            if (currAjax != null) {
                currAjax.abort();

            }
            currAjax = jqXHR;
         },
         url: ajaxurl,
         data: orderdata,
         dataType: 'text',
         success: function (response) {
             alert(response);
         }

    }); //end Ajax

} //end function

//Run the above function on submitting a form.
jQuery('#updateOrder').on('submit', function(event) {
    event.preventDefault();
    update_order();
});

The files are inside a folder inside plugin folder "http://localhost/test/wordpress/wp-content/plugins/update-order/template"

Inside that folder I have:

function update_order_ajax() {
    print_r( $_POST['data'] );
    wp_die(); // this is required to terminate immediately and return a proper response
}

add_action( 'wp_ajax_update_order_ajax', 'update_order_ajax' );

But I get:

POST http://localhost/test/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)

I searched and viewed many related question and tried to use a custom URL for the admin-ajax.php, Also checked the errors file, But couldn't find any solution.

I checked the admin-ajax.php and I see that it returns 400, When:

  • $_REQUEST['action'] is empty.
  • ! has_action( 'wp_ajax_' . $_REQUEST['action'] )
  • ! has_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] )

What is the problem?

  • Have you confirmed that you're actually loading the file you mention in the /plugins/update-order/template directory? – bosco Aug 14 '18 at 19:22
  • @bosco, Yes in the plugin file include_once plugin_dir_path(__FILE__) . '/template/file.php'; – Bon Aug 14 '18 at 19:25
  • I discovered the problem, The function was inside an included file and it seems that the ajax functions should be inside the main plugin file – Bon Aug 14 '18 at 19:33
  • That's not correct at all. The AJAX functions can absolutely be in an included file. If it only worked after moving the functions to the main plugin file then you must be included the file incorrectly. plugin_dir_path() includes a trailing slash, so try removing the slash from the beginning of '/template/file.php';. – Jacob Peattie Aug 15 '18 at 10:22

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.