Wordpress: Ajax request logs 400 Bad Request to co

2019-07-31 10:59发布

I keep getting this error:

POST http://localhost/wptest2/wp-admin/admin-ajax.php 400 (Bad Request)
(anonymous) @ VM12565:1
send @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
ajax @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
(anonymous) @ options-general.php?page=fvc-settings:784
dispatch @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:3
r.handle @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:3
  1. In the code below, ajaxPost() is hooked to the admin footer of my plugin.
  2. On clicking the button selected by jQuery, it should fire the registered post request and return a simple response.

This is not what happens with jQuery.post() or $.ajax(). I tried several things mentioned below in the comments but can't get it working, can anyone tell the issue?

function ajaxPost() {
  ?>

  <script>     
    jQuery(document).ready(function($) {        
      $('#previousButton').click(function() {
        var postData = {
          action : 'selectTargetsWithOffset',
          data : {
            offsetMultiplier : 1,
            incrementSize : 10
          },
          success : function(response) {
            console.log(`=====jQuery success=====`);
          }
        };

        var handleResponse = function(response) {
          console.log(response, `=====response=====`);
        };

        jQuery.post(ajaxurl, postData, handleResponse);

        // this code also threw a 400 error when 
        // I commented out the above code instead
        // $.ajax({
        //   type: "POST",
        //   url: ajaxurl,
        //   dataType: "json",
        //   data: {
        //     action: "selectTargetsWithOffset",
        //   },
        //   success: function() {
        //     console.log(response, `=====response 
        //       from $.ajax}=====`);
        //   }
        // });

      })

    })
  </script>
  <?php
}
add_action('admin_footer', 'ajaxPost');


function selectTargetsWithOffset() {
  wp_send_json([ 'message' => 'from back end' ]);
  wp_die();
}
add_action('wp_ajax_selectTargetsWithOffset', 'selectTargetsWithOffset');

Also tried - Going into admin-ajax.php and changing the response code from 400 to 420 to see if it would do anything. I did get some wierd error reflecting the change.

if ( is_user_logged_in() ) {
// If no action is registered, return a Bad Request response.
if ( ! has_action( "wp_ajax_{$action}" ) ) {
    wp_die( 'Test', 420 );
}

Adding the following to the top of admin-ajax.php:

  ?>
    <script>
      console.log(`=====TEST=====`);
      var request = "<?php echo $_REQUEST ?>";
      console.log(request['action'], `=====request=====`);
    </script>
  <?php

When I try to trigger the ajax call in my admin area, I still get the 400 bad response console log only. However when I directly navigate to the URL, now I see the ===TEST=== statement and request is marked as undefined (as I would expect). I take this to mean something about how I call the ajax request is wrong.

Here is my HTML code for the button that does the call:

<button id="previousButton">Previous</button>

In response to the simplified callback suggestion

Here is the console log:

=====jQuery success=====
VM13659:1 POST http://localhost/wptest2/wp-admin/admin-ajax.php 400 (Bad Request)
(anonymous) @ VM13659:1
send @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
ajax @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
n.(anonymous function) @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4
(anonymous) @ options-general.php?page=fvc-settings:785
dispatch @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:3
r.handle @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:3

And here is the code:

function ajaxPost() {
  ?>
  <script>

    jQuery(document).ready(function() {
      jQuery('#previousButton').click(function() {

        var postData = {
          action : 'selectTargetsWithOffset',
          data : {
            offsetMultiplier : 1,
            incrementSize : 10
          },
          success : function(response) {
            console.log(`=====jQuery success=====`);
          }
        };

        var handleResponse = function(response) {
          console.log(response, `=====response=====`);
        };

        jQuery.post(ajaxurl, postData, handleResponse);
      }); 
    })
  </script>
  <?php
}
add_action('admin_footer', 'ajaxPost');


function selectTargetsWithOffsetcb() {
  print_r($_POST);
  die();
}

add_action( 'wp_ajax_selectTargetsWithOffset', "selectTargetsWithOffsetcb");
add_action( 'wp_ajax_nopriv_selectTargetsWithOffset', "selectTargetsWithOffsetcb" );

There is no print_r() output on the page itself, it stays the same without any refreshing

It is worth noting again that the debug code ====TEST=== in admin-ajax.php failed to log. I think this indicates the request doesn't reach that file for some reason (since navigating to that file in browser does cause it to log to console)


Also tried this, but also a 400 error:

function ajaxPost() {
  ?>
  <script>    
    jQuery(document).ready(function() {
     jQuery(document).on("click","#previousButton", function() {
       jQuery.ajax({
         url: "<?php echo admin_url( 'admin-ajax.php' ) ?>",
         data: {"action":"selectTargetsWithOffset","datas": {"name": "yourfields"}},
         type:"post",
         success: function(data) { alert(data); }
       })
     });    
    })
  </script>
  <?php
}
add_action('admin_footer', 'ajaxPost');

1条回答
ゆ 、 Hurt°
2楼-- · 2019-07-31 11:51

I think you have not declared callback functions in your plugin or function file.

Please add below code to your plugin or fn file and test it.

add_action( 'wp_ajax_selectTargetsWithOffset', "selectTargetsWithOffsetcb");
add_action( 'wp_ajax_nopriv_selectTargetsWithOffset', "selectTargetsWithOffsetcb" );

function selectTargetsWithOffsetcb()
{

    print_r($_POST);
    die();
}

Also update this js

    <script>
jQuery(document).on("click","#previousButton",function(){

jQuery.ajax({
url:"<?php echo admin_url( 'admin-ajax.php' ) ?>",
data:{"action":"selectTargetsWithOffset","datas":{"name":"yourfields"}},
type:"post",
success:function(data){alert(data);}
})
});
</script>
查看更多
登录 后发表回答