0

I am trying to save the values of multiple checklists using update_option and individual options for each item. I am getting a 400 Error in the console when making POST requests to /wp-admin/admin-ajax.php. Please help if you can!

index.php:

function settings_html_content() {
    $details = get_option('details-checkbox');
    $socials = get_option('socials-checkbox');
    $topic_wheel = get_option('topic-wheel-checkbox');
    $testimonials = get_option('testimonials-checkbox');

    ?>
    
        <h2>Setup Checklist</h2>
        <form id="autosave-checklist-form" action="options.php">                                                                       
            <label for="details" id="details" name="details"><input type="checkbox" id="details" name="details" label="details" value="<?php echo esc_attr($details); ?>" <?php checked($details); ?>>Submit the <a href="?page=bm-plugin&tab=details">"Personal Branding Details" form</a>.</label>
            <label for="socials"  id="socials" name="socials"><input type="checkbox" id="socials" name="socials" label="socials" value="<?php echo esc_attr($socials); ?>" <?php checked($socials); ?>>Submit the <a href="?page=bm-plugin&tab=socials">"Social Media Accounts" form</a>.</label>
            <label for="topic-wheel" id="topic-wheel" name="topic-wheel"><input type="checkbox" id="topic-wheel" name="topic-wheel" label="topic-wheel" value="<?php echo esc_attr($topic_wheel); ?>" <?php checked($topic_wheel); ?>>Submit the <a href="?page=bm-plugin&tab=topic-wheel">"Topic Wheel" form</a>.</label>
            <label for="testimonials" id="testimonials" name="testimonials"><input type="checkbox" id="testimonials" name="testimonials" label="testimonials" value="<?php echo esc_attr($testimonials); ?>" <?php checked($testimonials); ?>>Submit the <a href="?page=bm-plugin&tab=testimonials">"Testimonials" form</a>.</label>
            <p>For more information please read our <a href="">documention</a>.</p>
            <?php
                settings_fields( 'checklist_settings_group' );
                do_settings_sections( 'bm_plugin' );
                submit_button();
            ?>
        </form>                                                        
    <?php
}

function autosave_checklist_handler() {                                 
    // $json_input = json_decode(file_get_contents('php://input'), true);

    // Get the checklist item value from the AJAX request                    
    $option = $_POST['option'];                                                  
    $item = $_POST['item'];
                                                                             
    // Update the checklist in the options table                             
    // update_option($option, $item); 
    update_option( $_POST['option'], $_POST['item'] );     
    ?>
        <div>
            <ul>
                <li> 
                    Option: <?php echo $option ?>
                </li>
                <li> 
                    Item: <?php echo $item ?>
                </li>
            </ul>       
        </div> 
    <?php    
    
    // Return a success response                                             
    wp_send_json_success(array('details: ' => true));
}   
add_action('wp_ajax_autosave_checklist', 'autosave_checklist_handler');
add_action('wp_ajax_nopriv_autosave_checklist', 'autosave_checklist_handler');  

function register_bm_settings() { 
    register_setting( 'checklist_settings_group', 'details-checkbox' );
    register_setting( 'checklist_settings_group', 'socials-checkbox' );
    register_setting( 'checklist_settings_group', 'topic-wheel-checkbox' );
    register_setting( 'checklist_settings_group', 'testimonials-checkbox' );
}

function bm_css_and_js($hook) {

    wp_enqueue_style('bm_css', plugin_dir_url(__FILE__).'css/styles.css');

    wp_enqueue_script('autosave-checklist-script', plugin_dir_url(__FILE__).'autosave-checklist.js', array('jquery'), '1.0', true);                    
    wp_localize_script(
        'autosave-checklist-script', 
        'autosaveChecklist',     
        array(                                                                       
            'ajaxUrl' => admin_url('admin-ajax.php') 
        )
    );
}

function bm_add_admin_page() {

    add_menu_page(
        'BlitzMetrics', 
        'BlitzMetrics', 
        'manage_options', 
        'bm-plugin', 
        'bm_admin_page_html',
        plugin_dir_url(__FILE__).'/images/icon.png'
      );

}

add_action( 'admin_enqueue_scripts', 'bm_css_and_js' );
add_action( 'admin_init', 'register_bm_settings' );

autosaving-checklist.js:

document.addEventListener('DOMContentLoaded', () => {
    const details = document.querySelector('#details');
    const socials = document.querySelector('#socials');
    const topicWheel = document.querySelector('#topic-wheel');
    const testimonials = document.querySelector('#testimonials');

    details.addEventListener('change', () => {
        console.log('autosaveChecklist: ' + JSON.stringify(autosaveChecklist))
        console.log('details: ' + details.checked)
        fetch(autosaveChecklist.ajaxUrl + '?action=wp_ajax_autosave_checklist', {
            method: 'POST',
            body: {
                action    : 'wp_ajax_autosave_checklist',
                option: 'details-checkbox',
                item: document.getElementById('details').checked
            },
            headers: {
            'Content-Type': 'application/json',
            },
        })
        .then(res => console.log(res))
        .catch(err => console.error(err));
    });

    socials.addEventListener('change', () => {
        console.log('autosaveChecklist: ' + JSON.stringify(autosaveChecklist))
        console.log('socials: ' + socials.checked)
        fetch(autosaveChecklist.ajaxUrl + '?action=wp_ajax_autosave_checklist', {
            method: 'POST',
            body: JSON.stringify({
                action    : 'wp_ajax_autosave_checklist',
                option: 'socials-checkbox',
                item: document.getElementById('socials').checked
            }),
            headers: {
            'Content-Type': 'application/json',
            },
        })
        .then(res => console.log(res))
        .catch(err => console.error(err));
    });

    topicWheel.addEventListener('change', () => {
        console.log('autosaveChecklist: ' + JSON.stringify(autosaveChecklist))
        console.log('topicWheel: ' + topicWheel.checked)
        fetch(autosaveChecklist.ajaxUrl + '?action=wp_ajax_autosave_checklist', {
            method: 'POST',
            body: JSON.stringify({
                action    : 'wp_ajax_autosave_checklist',
                option: 'topic-wheel-checkbox',
                item: document.getElementById('topic-wheel').checked
            }),
            headers: {
            'Content-Type': 'application/json',
            },
        })
        .then(res => console.log(res))
        .catch(err => console.error(err));
    });

    testimonials.addEventListener('change', () => {
        console.log('autosaveChecklist: ' + JSON.stringify(autosaveChecklist))
        console.log('testimonials: ' + testimonials.checked)
        fetch(autosaveChecklist.ajaxUrl + '?action=wp_ajax_autosave_checklist', {
            method: 'POST',
            body: JSON.stringify({
                action    : 'wp_ajax_autosave_checklist',
                option: 'testimonials-checkbox',
                item: document.getElementById('testimonials').checked
            }),
            headers: {
            'Content-Type': 'application/json',
            },
        })
        .then(res => console.log(res))
        .catch(err => console.error(err));
    });
})

1 Answer 1

0

Solved by using Content-Type: application/x-www-form-urlencode with new URLSearchParams(body).toString() instead of JSON.stringify(body).

autosave-checklist.js

details.addEventListener('change', () => {
        fetch(autosaveChecklist.ajaxUrl + '?action=autosave_checklist', {
            method: 'POST',
            body: new URLSearchParams({
                action    : 'autosave_checklist',
                option: 'details-checkbox',
                item: details.checked
            }).toString(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        })
        .then(res => console.log(res))
        .catch(err => console.error(err));;
    });

    socials.addEventListener('change', () => {
        fetch(autosaveChecklist.ajaxUrl, {
            method: 'POST',
            body: new URLSearchParams({
                action    : 'autosave_checklist',
                option: 'socials-checkbox',
                item: socials.checked
            }).toString(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        })
        .then(res => console.log(res))
        .catch(err => console.error(err));
    });

    topicWheel.addEventListener('change', () => {
        // console.log('topicWheel: ' + topicWheel.checked)
        fetch(autosaveChecklist.ajaxUrl, {
            method: 'POST',
            body: new URLSearchParams({
                action    : 'autosave_checklist',
                option: 'topic-wheel-checkbox',
                item: topicWheel.checked
            }).toString(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        })
        .then(res => console.log(res))
        .catch(err => console.error(err));;
    });

    testimonials.addEventListener('change', () => {
        // console.log('testimonials: ' + testimonials.checked)
        fetch(autosaveChecklist.ajaxUrl, {
            method: 'POST',
            body: new URLSearchParams({
                action    : 'autosave_checklist',
                option: 'testimonials-checkbox',
                item: testimonials.checked
            }).toString(),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        })
        .then(res => console.log(res))
        .catch(err => console.error(err));;
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.