How to do the simplest possible frontend ajax call from a plugin?

Question

I’m trying to make this as simple as possible just to get the basics down, but I keep getting a 400 error and 0 response from admin-ajax.php. I just want to hit ajax with some data. Here’s my js:

jQuery(document).ready(function($) {
  $('body').click(function(e){
      $.ajax({
          action: 'the_ajax_hook',
          data: 'field=data',
          type: 'post',
          url: the_ajax_script.ajaxurl,
          success: function(response_from_the_action_function) {
              $("#site-content").html(response_from_the_action_function);
          }
      });
  });
});

And here’s my plugin:

function load_my_scripts(){
     wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'ajax.js', array( 'jquery' ) );
     wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

add_action( 'wp_enqueue_scripts', 'load_my_scripts' );
add_action( 'wp_ajax_the_ajax_hook', 'the_action_function' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' ); 

function the_action_function(){
  echo "field is " . $_POST['field'];
  die();
}

The localization seems to work because it hits the right URL for admin_ajax, but it’s a bad request and returns nothing.

I know I’m missing something obvious but that’s the thing about obvious mistakes, they don’t seem obvious until someone else shows it to you. What am I missing?

0
, , pg. 4 years 2020-02-21T08:39:08-05:00 0 Answers 70 views 0

Leave an answer

Browse
Browse