0

I have used Wordpress Admin Ajax and the console shows that 400 (Bad Request)

    jQuery('#submitid').click(function(e){
    e.preventDefault();
    //var newCustomerForm = jQuery(this).serialize();

    jQuery.ajax({
        type: "POST",
        url: "wp-admin/admin-ajax.php",
        data: {status: 'status', name: 'name'},
        success:function(data){
             jQuery("#result").html(data);
        }
    });
});
Dev
  • 23
  • 1
  • 2

3 Answers3

4

The Wordpress AJAX process has some basic points that should be followed if you want it to work correctly:

1.In functions.php add the action you'd like to call from the frontend:

function logged_in_action_name() {
  // your action if user is logged in
}
function not_logged_in_action_name() {
  // your action if user is NOT logged in
}

add_action( 'wp_ajax_logged_in_action_name', 'logged_in_action_name' );
add_action( 'wp_ajax_nopriv_not_logged_in_action_name', 'not_logged_in_action_name' );

2.Register the localization object in functions.php

// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );

// Localize the script with new data
$some_object = array(
    'ajax_url' => admin_url( 'admin-ajax.php' )
);

wp_localize_script( 'some_handle', 'ajax_object', $some_object );

// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );

3.Create the AJAX request on the frontend

// source: https://codex.wordpress.org/AJAX_in_Plugins
var data = {
  'action': 'not_logged_in_action_name',
  'whatever': 1234
};

jQuery.post( ajax_object.ajax_url, data, function( response ) {
  console.log( response );
}
muka.gergely
  • 8,063
  • 2
  • 17
  • 34
  • 1
    Note: If you keep your ajax logic outside of functions.php file, don't forget to require the file in functions.php. – ado387 Feb 15 '22 at 21:52
1

All Wordpress Ajax call must have action param which points to hook wp_ajax_{action_param} or wp_ajax_nopriv_{action_param} and from there you jump to function from that hooks.

From Codex:

add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );

function my_action() {
    $status = $_POST['status'];
}
Kamil
  • 217
  • 4
  • 16
0

first you shouldn't write the url by yourself. You could use the localize function to add the url to your javascript file:

wp_enqueue_script('myHandle','pathToJS');

wp_localize_script(
   'myHandle',
   'ajax_obj',
    array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);

After this you can use ajax_obj.ajax_url within your script to receive the url.

Second, did you implement the correct hook?

// Only accessible by logged in users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// Accessible by all visitors
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );

Best Regards

Marc
  • 1
  • 1