I'm trying to do some form validation with Wordpress and jQuery Validate plugin. My js code is:
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
// submit reg-form
jQuery(document).ready(function ($) {
$.ajaxSetup({
cache: false
});
$("#username").change(function(){
$("#username").removeData("previousValue");
});
$("#moto_register").validate({
ignore: "",
rules: {
username: {
remote: {
url: ajaxurl,
type: "post",
data: {
username: function() {
return $( "#username" ).val();
},
action: 'moto_validate_username'
}
}
},
},
submitHandler: function(form) {
var sData = $(form).serialize();
$.ajax({
url: ajaxurl,
async: false,
type: 'POST',
data: sData,
success: function (data) {
if (console.log) console.log(data);
location.href = "http://test.net/?page_id=30 "
}
});
}
});
Im the Wordpress plugin I have following code:
function moto_validate_username() {
$user_id = username_exists( $_POST['username'] );
if ( !$user_id) echo 'true';
else echo 'false';
exit();
}
add_action( 'wp_ajax_nopriv_moto_validate_username', 'moto_validate_username' );
add_action( 'wp_ajax_moto_validate_username', 'moto_validate_username' );
this works SOMETIMES only, and sometimes doesn't. The AJAX seems to be actualy fired, but there's no response, and so no validation. Anyone has an idea why?
The problem seemed to be in removing the pages for non-admin users. When I changed it to:
function moto_remove_menu_pages() {
global $user_ID;
if (!$_POST['action'] == 'moto_validate_username') {
if ( $user_ID != '1' ) {
remove_menu_page('edit.php'); // Posts
remove_menu_page('upload.php'); // Media
remove_menu_page('link-manager.php'); // Links
remove_menu_page('edit-comments.php'); // Comments
remove_menu_page('edit.php?post_type=page'); // Pages
remove_menu_page('plugins.php'); // Plugins
remove_menu_page('themes.php'); // Appearance
remove_menu_page('tools.php'); // Tools
remove_menu_page('options-general.php'); // Settings
remove_submenu_page( 'index.php', 'update-core.php' );
}
}
}
add_action( 'admin_init', 'moto_remove_menu_pages' );
it magically started to work.
You should avoid the admin_init
hook to remove menu_pages and submenu_pages, because it can create conflicts with AJAX (see https://wordpress.org/support/topic/conflict-with-ajax-due-to-debug-warning).
Bind to the admin_menu
hook instead. If you have trouble removing some of the pages, bind with a very high priority. E.g. to remove theme-editor.php
you need to set a priority of about 120. For Jetpack pages, you need somthing around 2000.
add_action( 'admin_menu', 'moto_remove_menu_pages', 2000 );
This is also stated in the Wordpress Codex.