首页 > 解决方案 > '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);
  });
});

标签: ajaxwordpress

解决方案


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);
      });
    });
    

推荐阅读