Bad request 400 from custom ajax call

Question

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

});
0
, JPL 1 year 2020-07-21T13:11:56-05:00 0 Answers 47 views 0

Leave an answer

Browse
Browse