Wordpress admin-ajax.php 400 bad request

前端 未结 4 1114
無奈伤痛
無奈伤痛 2020-12-06 19:40

I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 400 error bad request.

(function( $ ) {
          


        
相关标签:
4条回答
  • 2020-12-06 20:05

    In Vanilla JavaScript You get a Bad Request if You don't append this header to the POST request:

    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
    

    So please be sure that jQuery appends as well that header.

    0 讨论(0)
  • 2020-12-06 20:08

    In my case, I am using Class based approach. And I found the issue was because I was using wp_ajax_ request in constructor.

    If you are using ajax methods inside class, move wp_ajax_ handles outside of class (write in main plugin file) and pass classname and method name. For example:

    add_action( 'wp_ajax_your_handle', [ 'Class_Name', 'function_name' ] );
    add_action( 'wp_ajax_nopriv_your_handle', [ 'Class_Name', 'function_name' ] ); 
    
    0 讨论(0)
  • 2020-12-06 20:27

    I have modified your code and look at this :

    (function( $ ) {
    var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
    $.ajax({
        url : ajaxscript.ajax_url,
        data : {
            action : 'post_cart_clb',
            id : 1
        },
        method : 'POST', //Post method
        success : function( response ){ console.log(response) },
        error : function(error){ console.log(error) }
      })
    })(jQuery)
    

    This is the syntax of WordPress ajax : wp_ajax_{Your_action_name} wp_ajax_nopriv_{Your_action_name}

    0 讨论(0)
  • 2020-12-06 20:30

    First, use full and absolute url, with protocol (or at least protocol-independent form):

    var ajaxscript = { ajax_url : '//mydomain.com/wp-admin/admin-ajax.php' } 
    

    Second, your ajax action name is not the php callback function name but the dynamic part of the hook wp_ajax_{action_name} / wp_ajax_nopriv_{action_name}, so in your case it should be:

    data : {
        action : 'post_cart_clb',
        id : 1
    },
    
    0 讨论(0)
提交回复
热议问题