0

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

From codex: wp_ajax_{$action} and wp_ajax_nopriv{$action} the dinamic part {$action} must be the same name as the function, so instead of:

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

do:

add_action( 'wp_ajax_the_action_function', 'the_action_function' );
add_action( 'wp_ajax_nopriv_the_action_function', 'the_action_function' );
| improve this answer | |
1

You should pass data as data: {action: 'actionname', filed: data},. So your data is variable which contain data. So your code look like below:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.