简体   繁体   中英

'Bad request' (400) error with WordPress Ajax

I don't understand why I get a 400 'bad request' error with the Ajax code below. I don't get any Apache error btw:

PHP (functions.php)

function load_scripts() {
  wp_enqueue_script('jquery');  
  wp_enqueue_script('main_js', get_stylesheet_directory_uri() . '/dist/scripts/main.js', array('jquery'), true);
  wp_localize_script('main_js', 'WPaAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'load_scripts');

function send_message_function() {
  echo 'YES!';
  exit;
}

add_action('wp_ajax_send_message', 'send_message_function');
add_action('wp_ajax_nopriv_send_message', 'send_message_function');

JS (main.js)

$('.contact_form').submit(function(e) {
  e.preventDefault();
  var data = $(this).serializeArray();
  $.post(WPaAjax.ajaxurl, data, function(response) {
    $('body').append(response);
  });
});

The Bad Request error message you're seeing is because WordPress considers your request -wait for it- invalid:

  1. You're passing an array of objects to $.post when it expects a plain object or a string. You want to use FormData instead:

     $('.contact_form').submit(function(e) { e.preventDefault(); var data = new FormData($(this)[0]); $.post(WPaAjax.ajaxurl, data, function(response) { $('body').append(response); }); }); 

and:

  1. WordPress expects the action parameter to be included with your request, which seems to be missing from your code. So:

     $('.contact_form').submit(function(e) { e.preventDefault(); var data = new FormData($(this)[0]); data.append("action", "send_message"); $.post(WPaAjax.ajaxurl, data, function(response) { $('body').append(response); }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM