seceparsto
seceparsto

Reputation: 21

Wordpress AJAX not sending and give admin-ajax.php error 400

I am trying to make an AJAX call on Wordpress but it is giving me an 400 error on admin-ajax.php. I think I have all the enqueues actions correctly setup. Maybe I have still missed out one tiny error. Please help.

I have double-checked that the location of admin-ajax.php and the .js file are correct. I have also tried enqueuing the .js file directly without registering it first, and calling admin-ajax.php directly at without the array.

I have the following error: POST https: .../wp-admin/admin-ajax.php 400 jQuery.ajax({ <- this is the line where the error occurs).

The AJAX call has not been sent.

functions.php


add_action( 'wp_enqueue_scripts', 'lp_load_scripts' );
function lp_load_scripts() {
    wp_register_script( 'lp-script',get_stylesheet_directory_uri(). '/inc/js/admin.js', array('jquery'), NULL, true );
    wp_enqueue_script('lp-script');
    wp_localize_script( 'lp-script', 'lp_ajax', array('ajaxurl'=>admin_url( 'admin-ajax.php' )) );

}

add_action( 'wp_ajax_list_papers', 'list_papers' );
add_action( 'wp_ajax_nopriv_list_papers', 'list_papers' );
function list_papers() {
    $data = $_POST['key'];
    echo($data);
    wp_die();
}

admin.js

jQuery(document).ready(function($) {
  jQuery('.find-paper').on('click',(e)=>{
    var jsondata = JSON.stringify({
      key: "listpapers",
      urn: $('#urn').val(),
      action: "list_papers",
    });
    console.log(jsondata);
    jQuery.ajax({
      url: lp_ajax.ajaxurl,
      type: "post",
      data: jsondata ,
      success: function(response){
        console.log(response);
      },
      error: function(e) {
         console.log(e);
      },
    }) 
  })
})

HTML

<input type="text" name="urn" id="urn">
<input type="button" class="find-paper" id="find-paper" value="find papers">

Upvotes: 0

Views: 1412

Answers (1)

seceparsto
seceparsto

Reputation: 21

OK. I finally solve the problem.

** Do NOT JSON.stringify the data object. **

Also, no need to add dataType: 'json' either.

Error 400 has now gone.

Upvotes: 1

Related Questions