最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Bad request 400 from custom ajax call

programmeradmin2浏览0评论

I tried everything I think but still getting bad request 400 Ajax WordPress. I have try applying serialize and answers found in other thread but still getting 400 bad error.

Custom Page Template index.php

add_action( 'wp_enqueue_scripts', 'myblog_ajax_enqueue' );
function myblog_ajax_enqueue() {
  wp_enqueue_script('myblog-ajax-script', get_stylesheet_directory_uri() . '/template-parts/templates/blog/js/ajax.js',array('jquery'));
  wp_localize_script(   'myblog-ajax-script','myblog_ajax_obj', array('ajaxurl' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajax-nonce')));
}

blogcontent.php

function myblog_ajax_request() {
    $nonce = $_POST['nonce'];
    if ( ! wp_verify_nonce( $nonce, 'myblog-ajax-script' ) ) {
        die( 'Nonce value cannot be verified.' );
    }
    // The $_REQUEST contains all the data sent via ajax
    if ( isset($_REQUEST) ) {
        $fruit = $_REQUEST['fruit'];
        // Let's take the data that was sent and do something with it
        if ( $fruit == 'Banana' ) {
            $fruit = 'Apple';
        }
        echo $fruit;
    }
   die();
}

add_action( 'wp_ajax_myblog_ajax_request', 'myblog_ajax_request' );
add_action( 'wp_ajax_nopriv_myblog_ajax_request', 'myblog_ajax_request' );

Ajax.Js

jQuery(document).ready(function($) {


  var fruit = 'Banana';

  // This does the ajax request
  $.ajax({
    url: myblog_ajax_obj.ajaxurl,
    data: JSON.stringify({
      'action': 'myblog_ajax_request',
      'fruit': fruit,
      'nonce': myblog_ajax_obj.nonce
    }),
    success: function(data) {
      // This outputs the result of the ajax request
      console.log(data);
    },
    error: function(errorThrown) {
      console.log(errorThrown);
    },
    dateType: 'json',
    contentType: 'application/json; charset=utf-8'
  });

});

I tried everything I think but still getting bad request 400 Ajax WordPress. I have try applying serialize and answers found in other thread but still getting 400 bad error.

Custom Page Template index.php

add_action( 'wp_enqueue_scripts', 'myblog_ajax_enqueue' );
function myblog_ajax_enqueue() {
  wp_enqueue_script('myblog-ajax-script', get_stylesheet_directory_uri() . '/template-parts/templates/blog/js/ajax.js',array('jquery'));
  wp_localize_script(   'myblog-ajax-script','myblog_ajax_obj', array('ajaxurl' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajax-nonce')));
}

blogcontent.php

function myblog_ajax_request() {
    $nonce = $_POST['nonce'];
    if ( ! wp_verify_nonce( $nonce, 'myblog-ajax-script' ) ) {
        die( 'Nonce value cannot be verified.' );
    }
    // The $_REQUEST contains all the data sent via ajax
    if ( isset($_REQUEST) ) {
        $fruit = $_REQUEST['fruit'];
        // Let's take the data that was sent and do something with it
        if ( $fruit == 'Banana' ) {
            $fruit = 'Apple';
        }
        echo $fruit;
    }
   die();
}

add_action( 'wp_ajax_myblog_ajax_request', 'myblog_ajax_request' );
add_action( 'wp_ajax_nopriv_myblog_ajax_request', 'myblog_ajax_request' );

Ajax.Js

jQuery(document).ready(function($) {


  var fruit = 'Banana';

  // This does the ajax request
  $.ajax({
    url: myblog_ajax_obj.ajaxurl,
    data: JSON.stringify({
      'action': 'myblog_ajax_request',
      'fruit': fruit,
      'nonce': myblog_ajax_obj.nonce
    }),
    success: function(data) {
      // This outputs the result of the ajax request
      console.log(data);
    },
    error: function(errorThrown) {
      console.log(errorThrown);
    },
    dateType: 'json',
    contentType: 'application/json; charset=utf-8'
  });

});
Share Improve this question edited Jul 21, 2020 at 17:12 mozboz 2,6281 gold badge12 silver badges23 bronze badges asked Jul 21, 2020 at 12:16 JPLJPL 1372 silver badges11 bronze badges 3
  • You’re sending the data as JSON: JSON.stringify. This won’t work because $_POST['action'] won’t be populated. See the example from the documentation: developer.wordpress/plugins/javascript/ajax/… – Jacob Peattie Commented Jul 21, 2020 at 12:24
  • I have also tried that, you can see the original code here gist.github/devinsays/69a305053e35a10584f94d6011bba2d6 but still getting 400 bad error – JPL Commented Jul 21, 2020 at 12:52
  • Have you considered using the REST API to handle AJAX instead? It gives human readable error messages rather than a HTTP code and 0, has pretty URLs, it'll even handle authentication checking for you with a few extra parameters – Tom J Nowell Commented Jul 21, 2020 at 13:22
Add a comment  | 

3 Answers 3

Reset to default 3

There's only one reason you get a 400 error with admin-ajax.php: The wp_ajax_{$action} or wp_ajax_nopriv_{$action} action has not been hooked with an {$action} that matches the action data parameter sent with your request. So either your callback is not hooked, or you're not sending the action correctly. Your code is making both errors.

  1. You are encoding the data sent to the server as JSON. WordPress looks for $_REQUEST['action'] to trigger the appropriate action. When data is sent to the server as JSON, $_REQUEST cannot be populated, so $_REQUEST['action'] does not exist, meaning that your callback is never run. You need to remove JSON.stringify() from your code.
  2. You are running add_action() for wp_ajax_myblog_ajax_request inside a page template. This won't work. You are sending your request to wp-admin/admin-ajax.php, but that code does not load templates, so your callback is not hooked for that request. You need to use add_action() inside a file that is loaded inside wp-admin/admin-ajax.php, such as your theme's functions.php file, or a plugin.

Here is your problem:

blogcontent.php

When WP is contacted to handle the Admin AJAX request, it doesn't load a page template. Remember, every request to WP loads WP from a blank slate. It doesn't know anything about the previous requests, only what it's told.

So because you aren't requesting that page, the template never loads, the filters never run, so there is no AJAX handler to take your request.

So instead, move your filters to functions.php. Also consider using the modern REST API to handle your requests, it's easier, nicer to debug with human readable error messages, and it'll sanitize authenticate and validate for you if you tell it how! You even get a nice friendly URL.

Once that's been done, undo all the other things you did to try and fix this, like setting the datatype, or contenttype, that's hurting you not helping.

  1. Send is as object, not a JSON string

  2. Remove content type, you should let is default ( application/x-www-form-urlencoded)

  3. Remove dataType - you send response as text, not a json. ( for JSON response use wp_send_json )

  4. Ensure that you register you ajax actions in init files ( your plugin main file or functions.php )

  5. Also you can try debug it step by step in wp-admin/admin-ajax.php. 400 error means you code get this file, but action isnt recognized

     url: myblog_ajax_obj.ajaxurl,
     data: {
       action: 'myblog_ajax_request',
       fruit: fruit,
       nonce: myblog_ajax_obj.nonce
     },
     success: function(data) {
       console.log(data);
     }
    
发布评论

评论列表(0)

  1. 暂无评论