Support » Developing with WordPress » admin-ajax error 400

  • Resolved sutheodor

    (@sutheodor)


    When I make an AJAX call I receive the “/wp-admin/admin-ajax.php 400 (Bad Request)” error
    This is my PHP

    add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
    
       public function enqueue() {
            wp_enqueue_script( 
                'ajax-script',
                plugin_dir_url( __FILE__ ) . '/ajax.js',
                array( 'jquery' )
            );
    
            wp_localize_script( 
                'ajax-script',
                'wp_ajax',
                array( 
                    'ajaxurl' => admin_url( 'admin-ajax.php' ),
                    'dede' => 1234
                )                 
            );
        }
    
    add_action( 'wp_get_data', array( $this, 'get_data') );
    
    public function get_data() {
        $whatever = intval( $_POST['whatever'] );
        $whatever += 10;
        $whatever;
        wp_die(); 
    }
    

    and this is my ajax.js

    jQuery(document).ready(function ($) {
    
        var data = {
            'action': 'get_data',
            'whatever': wp_ajax.dede
        };
    
        jQuery.ajax({
    		url : wp_ajax.ajaxurl,
    		type : 'post',
    		data : data,
    		success : function( response ) {
                console.log(response);
    		}
    	});
    
    });
Viewing 2 replies - 1 through 2 (of 2 total)
  • Ramiz Manked

    (@ramizmanked)

    Hi @sutheodor

    I think, you should consider using wp_ajax and wp_ajax_nopriv for processing Ajax data into callback funtions.

    In your case:

    add_action( ‘wp_ajax_get_data’, ‘get_data’ );
    add_action( ‘wp_ajax_nopriv_get_data’, ‘get_data’ ); // If you are handling AJAX requests from unauthenticated users.

    public function get_data() {
    // your code goes here.
    }

    sutheodor

    (@sutheodor)

    Thanks @ramizmanked u solved my problem

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘admin-ajax error 400’ is closed to new replies.