2

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!

  • What info are you getting in the console when you debug? – Tony Djukic Mar 31 at 5:31
  • Nothing. If I put console.log(user_setts); right after var user_setts = user_setts; in the ajax file, it outputs "Undefined" – Edegist Mar 31 at 6:39
  • var user_setts = user_setts; doesn’t get the value from anywhere. (I’m on my phone so can only look at segments of the code at a time, sorry if I missed it.) – Tony Djukic Mar 31 at 6:49
  • Thanks. When you have a chance, do you mind helping me get the value to ajax properly? I would really appreciate the help! Thanks! – Edegist Mar 31 at 6:56
  • I'm off to bed as it's 3:30am and I've got to be up and coding by 7:30am - if you're still stuck or my answer doesn't help at all, I can try and look at it again in the morning. Best of luck. – Tony Djukic Mar 31 at 7:25
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
        }
| improve this answer | |
  • Thanks for your response! I modified line 1 of the ajax file to jQuery(document).ready( function($) { and changed jQuery.ajax({ to $.ajax({ and now it is properly logging the values. However WordPress doesn't seem to be saving the data. On the dev Network page admin-ajax.php returns a status of "(canceled)", and there is no response. – Edegist Mar 31 at 17:45
  • Edit: I also noticed that it is outputting all the values in the checkbox array - not just the items that are selected. – Edegist Mar 31 at 17:58
  • Thanks! The array is now working, but the nonce change generates this error : Uncaught ReferenceError: nonce is not defined – Edegist Mar 31 at 18:25
  • I still get a problem with admin-ajax.php: XHR failed loading: POST ".../wp-admin/admin-ajax.php". Also, I fired the console.log before var str = {. If I fire it at success, I get nothing. Also, now in the Network tab, admin-ajax.php has a status of 200, but response is still blank. – Edegist Mar 31 at 18:56
  • Edit: console.log( user_categories + ' : ' + str ); at success is outputting 22,21,17 : [object Object] . – Edegist Mar 31 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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