I have an array on a front end page, and I am trying to update user_meta with the array via AJAX on the click of a submit button. I have come up with the following code, but I am having problems with it. Currently when I hit submit, I get a 404 error: POST http://www..../wp-admin/admin-ajax.php 400 (Bad Request)
Here is what I got so far:
Form Example
<form name="myform" id="myform" method="POST">
<input name="user_categories[]" id="<?php echo $box_id ?>" value="<?php echo $box_val ?>" <?php echo $selected ?> type="checkbox"/>
<input name="myBtn" class="ajaxsubmitbutton" type="submit" value="Save Settings">
</form>
The Following is in a Plugin:
add_action( 'wp_footer', 'cf_ajax_save' ); // Write our JS below here
function cf_ajax_save() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
$('.ajaxsubmitbutton').click(function(){
var user_categories = user_categories
var data = {
action: 'aj_save_category_settings',
user_categories: user_categories
};
//ajaxurl is defined only because buddypress predefined it, and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
});
</script>
<?php
}
function aj_save_user_categories( $user_id ){
if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
update_usermeta( $user_id, 'user_categories', $_POST['user_categories'] );
wp_die(); // this is required to terminate immediately and return a proper response
}
//Hook Function into WP_Ajax for Admin and Frontend
add_action('wp_ajax_aj_save_category_settings', 'aj_save_user_categories');
add_action('wp_ajax_nopriv_aj_save_category_settings', 'aj_save_user_categories');
?>