0
votes

Hello everyone I am trying to use ajax in my custom plugin for wordpress but got an issue in my console showing 400 bad request in admin-ajax

  1. JS scripts

    public static function register_script(){
    
        wp_enqueue_script('ajaxscript', substr(plugin_dir_url(__FILE__), 0, -10) . '/assets/js/register-post.js', array( 'jquery', 'json2' ), '1.0.0', true );
    
        wp_localize_script( 'ajaxscript', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajaxnonce') ) );
    
    }
    
    1. Ajax

function signup(){
  // alert("working");

  jQuery('#registration').on('submit', function(e) {
    var data =  jQuery("#registration").serialize();
    e.preventDefault();
    // e.stopPropagation(); // only neccessary if something above is listening to the (default-)event too

      jQuery.ajax({
          type: 'POST',
          url: my_ajax_object.ajax_url,
          processData: false,
          data: {
            action: 'register_ajax_request&nonce='+ my_ajax_object.nonce,
            data: data
          },
          dataType: 'json',
          success: function(response) {
          if(response.success === true) {
               // jQuery("#vote_counter").html(response.vote_count)
            }else {
               // alert("Your vote could not be added")
            }
          }
          
        });   
      
    });
          
  }
  1. Registration Function

<?php
add_action('wp_ajax_register_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_nopriv_register_ajax_request', 'ajax_handle_request');


function ajax_handle_request(){

	if (isset($_POST['register_trigger'])){

		$nonce = $_POST['nonce']; 
		print_r($nonce);
		exit();
	}
}

Location of the registration.php is plugindirectory/inc/pages/. This is not a function.php like the wordpress theme.

enter image description here enter image description here

1
Did you try data: {action: 'register_ajax_request', data: data, nonce: my_ajax_object.nonce} - Banzay
What Banzay said. The action parameter should only include the name of your action (register_ajax_request) and nothing else. - cabrerahector
@Banzay it is still showing a bad 400 - Rjgapz
look at other section of console: i.stack.imgur.com/R9UfR.png - does form send any data? - Banzay
link, link @Banzay - Rjgapz

1 Answers

0
votes

Sorry I just forgot to include a php file that the action is looking for.