Search code examples
phpajaxwordpresswordpress-plugin-creation

wordpress plugin development boilerplate: ajax call response 400


im trying to call wp ajax in my plugin (i use boilerplate) but i retrive always:

http://wordpress-bricks.it/wp-admin/admin-ajax.php 400 (Bad Request)

i define my page in admin for option page:

<?php

class Consent_Dado_Admin {
private $plugin_name;
private $version;

public function __construct($plugin_name, $version) {
    $this->plugin_name = $plugin_name;
    $this->version = $version;
}

 public function enqueue_scripts() {
    $ajaxurl_arr = array('ajax_url' => admin_url('admin-ajax.php'));
    wp_enqueue_script('nds_ajax_handle2', plugin_dir_url(__FILE__) . 'js/consent-dado-admin.js', array('jquery'), $this->version, false);
    wp_localize_script('nds_ajax_handle2', 'ajaxurl_arr', $ajaxurl_arr);
}

public function create_admin_menu() {

    add_menu_page('Consent Dadomedia', 'CC Dadomedia', 'manage_options', 'cc-dado-menu', [$this, 'cc_dado_admin_page'], 'dashicons-buddicons-replies', '10');

    $ajax_form_page_hook2 = add_submenu_page('cc-dado-menu', 'Impostazioni', 'Impostazioni', 'manage_options', 'impostazioni-scan-dado', [$this, 'cc_dado_admin_setting_page']);

    add_action('load-' . $ajax_form_page_hook2, array($this, 'loaded_ajax_form_submenu_page2'));
}

public function cc_dado_admin_page() {
    include 'partials/cc-dado-admin-display.php';
}

public function cc_dado_admin_setting_page() {
    include 'partials/cc-dado-admin-setting-page.php';
}

public function ajax_form_page_content2() {
    // called when the particular page is loaded.
}

public function loaded_html_form_submenu_page2() {
    // called when the particular page is loaded.
}

public function loaded_ajax_form_submenu_page2() {
    // called when the particular page is loaded.       
}

public function create_admin_page() {
    $this->add_settings_section();
    $this->add_settings_fields();
    $this->save_options();
}

public function add_settings_section() {

    add_settings_section('cc-licence-section', 'Impostazioni licenza', function () {
        echo '<p>Per attivare le funzionalità del plugin, fornire un codice di licenza valido.</p>';
    }, 'cc-option-settings');
  
}

public function add_settings_fields() {

    add_settings_field(
            'id-licenza',
            'Numero di licenza',
            function () {
                echo '<input type="text" name="id-licenza" value="' . esc_html(get_option('id-licenza')) . '"/>
            <p class="description">Indicare il numero di licenza</p>';
            },
            'cc-option-settings', 'cc-licence-section', '');

}

public function save_options() {
    register_setting('cc-option-settings-group', 'id-licenza', ['sanitize_callback' => 'sanitize_text_field']);
}
}

while in my option page i define my form with this code:

<div class="wrap">
<h1>Cookie Consent - <?php echo get_admin_page_title() ?> </h1>

<form id="form_attivazione" method="post" action="options.php">
    <?php
    settings_fields('cc-option-settings-group');
    do_settings_sections('cc-option-settings');
    submit_button();
    ?>
</form>

<div id="answare"></div>

my javascript with ajax call have this code:

(function ($) {
'use strict';


$(window).load(function () {
    console.log(ajaxurl_arr.ajax_url)

    $('#form_attivazione').submit(function (event) {

        event.preventDefault();

        var ajax_form_data2 = $("#form_attivazione").serialize();

        console.log(ajax_form_data2)

        $.ajax({
            url: ajaxurl_arr.ajax_url, // domain/wp-admin/admin-ajax.php
            type: 'post',
            data: ajax_form_data2
        })

                .always(function () {
                    event.target.reset();
                })

                .done(function (response) {
                    $(" #answare ").html("<h2>The request was successful </h2><br>" + response);
                })


                .fail(function () {
                    $(" #answare ").html("<h2>Something went wrong.</h2><br>");
                });

    });

});

})(jQuery);

where is my mistake ? :/


Solution

  • You haven't define the function where the ajax request will be handled, Wp has it's own method to define an ajax URL

    add this 2 lines in your constructor

    add_action( 'wp_ajax_save_cc_dado_settings', array( $this , 'save_cc_dado_settings' ));
    add_action( 'wp_ajax_nopriv_save_cc_dado_settings', array( $this , 'save_cc_dado_settings' ));
    

    Now define the function where the AJAX needs to be handled inside the same class

    public function save_cc_dado_settings(){
       // write your logic for storing the data whatever you wants by $_POST or $_REQUEST 
    }
    

    Now where sending the ajax request add the action name like this

    data: { action : 'save_cc_dado_settings' }, // include other data with this as per your need.

    so basically this is the way to work with WP AJAX for better understanding you can check the documentation .