I want to make pre validation in some custom post type I made, I decided to do this with ajax, so I wrote this code: Enqeue the script:
function hazeracareer_admin_scripts(){
global $post_type;
if ( $post_type == 'job' ) {
$theme_uri = get_stylesheet_directory_uri();
wp_register_script('pre-job-submit-validation', $theme_uri . '/admin/js/pre-job-submit-validation.js', array('jquery'), '2133672');
wp_localize_script('pre-job-submit-validation', 'secure', array('nonce' => wp_create_nonce('hazeracareer_pre_job_submit_validation')));
wp_enqueue_script('pre-job-submit-validation');
}
}
add_action('admin_enqueue_scripts', 'hazeracareer_admin_scripts');
The JS file:
jQuery(document).ready(function ($) {
$('#post').submit(function () {
var form_data = $('#post').serialize();
var nonce = secure.nonce;
var data = {
action: 'hazeracareer_pre_job_submit_validation',
security: nonce,
form_data: form_data
};
$.post(ajaxurl, data, function (response) {
if ( response == 0 ) {
alert('The Job Number You entered is already exists in another job!');
return false;
} else {
return true;
}
});
});
});
Handle the ajax request and make the validation:
function hazeracareer_pre_job_submit_validation(){
check_ajax_referer('hazeracareer_pre_job_submit_validation', 'security');
$post = array();
parse_str($_POST['form_data'], $post);
if ( !isset($post['fields']['field_job_number']) )
return;
$jobs = get_posts(array(
'post_type' => 'job',
'post_status' => array('publish', 'draft'),
'posts_per_page' => -1,
'meta_key' => 'job_number',
'meta_value' =>$post['fields']['field_job_number']
));
if ( empty($jobs) ) {
echo 1;
}
echo 0;
wp_die();
}
add_action('wp_ajax_hazeracareer_pre_job_submit_validation', 'hazeracareer_pre_job_submit_validation');
But even though I get the error alert "The Job Number You entered is already exists in another job!", after I press OK the form does submit, and I get the admin notice that confirm the post was updated. After the alert I returned false so the form should not be submitted. I search in the web and nothing seems to work. What am I missing here?
Thanks in advance