Problem with WordPress Ajax form

I am trying to save data from a form to user meta using ajax, however I am unsuccesful.

I am pretty new to jQuery, and am not sure where I am going wrong, as there don’t seem to be any suntax errors.

Here is my code in my plugin file:

/**
     * Action hooks
     */
        // Register and Enqueue plugin styles and scripts
        add_action( 'wp_enqueue_scripts','load_css_and_js');
        function load_css_and_js() {
            wp_register_style( 'krv-style', plugin_dir_url( __FILE__ ) .'css/custom-setts.css' );
            wp_enqueue_style('krv-style');
            wp_register_script( 'krv-script', plugins_url( 'js/custom-setts.js', __FILE__ ), array('jquery'), null, false );
            wp_enqueue_script('krv-script');
            wp_localize_script( 'krv-script', 'krv_obj', array( 'ajax_url' => admin_url('admin-ajax.php'), 'check_nonce' => wp_create_nonce('krv-nonce') ) );
        }

        function aj_save_setts_settings( $user_id ) {
            check_ajax_referer( 'krv-nonce', 'security' );
            $krv_user_setts = $_POST['user_setts']; 

            if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
            update_usermeta( $user_id, 'user_setts', $krv_user_setts );
        }

        //Hook Function into WP_Ajax for Admin and Frontend
        add_action('wp_ajax_aj_save_setts_settings', 'aj_save_setts_settings');
        add_action('wp_ajax_nopriv_aj_save_setts_settings', 'aj_save_setts_settings');

        //Add [setts] Form Shortcode
        add_shortcode( 'setts', 'add_user_setts_shortcode' );
        function add_user_setts_shortcode(){
            ?>
            <!-- Create setts Checkbox Loop -->
            <div class="container">
                <form name="myform" id="myform" method="POST">
                    <ul class="ks-cboxtags">
                        <!-- (Loop) -->
                        <li><input name="user_setts[]" id="<?php echo $setts->term_id; ?>" value="<?php echo $setts->term_id; ?>" <?php echo $selected; ?> type="checkbox"/><label for="<?php echo $setts->term_id; ?>"><?php echo $setts->name; ?></label></li>
                    </ul>
                    <input name="myBtn" class="kvo_ajax_submit_button" type="submit" value="Save Settings">
                </form>
            </div>
            <?php
        }
?>

And this is what I have in js/custom-setts.js:

jQuery(document).ready( function() {
    jQuery('.kvo_ajax_submit_button').click(function(){

        var user_setts = user_setts;
        var str = {
                'action': 'aj_save_setts_settings',
                'security': krv_obj.check_nonce,
                'user_setts': user_setts,
            };
        jQuery.ajax({
                type: "POST",
                dataType: "html",
                url: krv_obj.ajax_url,
                data: str,
                success: function(data){
                    // Code after ajax success

                },
                error : function(jqXHR, textStatus, errorThrown) {
                    $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
                }
        });
    });

});

Any assistance is greatly appreciated!

1 Answer
1

Ok, after a lengthy discussion Edegist and I actually sorted this all out. Here’s a couple of the key factors that comprise the solution.

One, we had to loop through all of the selected checkboxes to pass via AJAX.

jQuery( document ).ready( function( $ ) {
    $( '.kvo_ajax_submit_button' ).click( function( e ) {
        e.preventDefault();
        var user_categories = $( 'input[name="user_categories\\[\\]"]' ).map( function() {
            if( $( this ).is( ':checked' ) ) {
                return $( this ).val();
            }
        } ).get();
        var str = {
            'action': 'aj_save_category_settings',
            'security': krv_obj.check_nonce,
            'user_categories': user_categories,
        };
        $.ajax({ 
            type: 'POST',
            dataType: 'html',
            url: krv_obj.ajax_url,
            data: str,
            success: function( data ) {
                // Code after ajax success
                console.log("Success");
            },
            error : function(req, err){
                console.log('Error:' + err);
            }
        } );
    } );
} );

The next step was figuring out why it wasn’t saving to the user_meta database. We realized that the AJAX wasn’t transmitting a $user_id, so we addressed that.

         function aj_save_category_settings( $user_id ) {
          $user_id = get_current_user_id();
            check_ajax_referer( 'krv-nonce', 'security' );
            $krv_user_categories = $_POST['user_categories'];
            if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
            update_user_meta( $user_id, 'user_categories', $krv_user_categories, false );
            wp_die(); // this is required to terminate immediately and return a proper response
        }

Leave a Comment