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

});
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.org/plugins/javascript/ajax/… Jul 21, 2020 at 12:24
  • I have also tried that, you can see the original code here gist.github.com/devinsays/69a305053e35a10584f94d6011bba2d6 but still getting 400 bad error
    – JPL
    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
    Jul 21, 2020 at 13:22

3 Answers 3

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.
2

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.

0
  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);
     }
    
7
  • that would the original code I have before adding JSON and was getting bad error. Also I am using a custom page template instead of a plugin
    – JPL
    Jul 21, 2020 at 12:59
  • 1
    So blogcontent.php is a page template? You can’t hook ajax callbacks inside a template. That code needs to go in functions.php. Jul 21, 2020 at 13:17
  • Jacob is right, by the time you're in the template it's too late, it needs to be done in a plugin or functions.php
    – Tom J Nowell
    Jul 21, 2020 at 13:23
  • okay so if I only want to trigger it in a particular page, does it mean I have to use is_page() ?
    – JPL
    Jul 21, 2020 at 22:13
  • @JacobPeattie which code are you referring to? index.php, blogcontent.php or ajax.js?
    – JPL
    Jul 21, 2020 at 22:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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