I have a number of functions that do a live ajax check on some fields; for example, a couple of seconds after the email
field is filled out, it fires an ajax check to see if that email is already being used by another account. I also want to use the same function for double-checking the values posted to the form overall. At the moment, it looks like something like this:
function ajax_checkEmailAddress($passedEmail = false) {
$isAjaxRequest = ($passedEmail === false);
$sentEmail = (!$isAjaxRequest) ? $passedEmail : sanitize_email($_POST['email'], true);
if (email_exists($sentEmail)) {
$jsonArray['response'] = 'error';
$jsonArray['message'] = __('This email address is already in use.', 'ajaxSignup');
} else {
$jsonArray['response'] = 'success';
}
if ($isAjaxRequest) {
wp_send_json($jsonArray);
} else {
return $jsonArray;
}
}
I subsequently have another ajax function that deals with processing the complete submitted form:
function ajax_processForm() {
$email = $_POST['email'];
$checkedEmail = ajax_checkEmailAddress($email);
if ($checkedEmail['response'] == 'success') {
// Continue processing the form actions
} else {
wp_send_json($checkedEmail);
}
}
add_action('wp_ajax_processForm', 'ajax_processForm');
add_action('wp_ajax_nopriv_processForm', 'ajax_processForm');
I don't want to double up on all of my error-checking functions, hence the use of the $passedEmail
parameter check, which defaults to false
; that way the function should know whether it's being called by ajax or by an internal function, and can return
the results array to the function instead of wp_send_json
, which would die()
.
However, using standard ajax listeners:
add_action('wp_ajax_checkEmailAddress', 'ajax_checkEmailAddress');
add_action('wp_ajax_nopriv_checkEmailAddress', 'ajax_checkEmailAddress');
...they always seem to send an empty parameter, so $passedEmail
never defaults to false
. Even if I try to default it with nonsense, it gets overwritten:
function ajax_checkEmailAddress($passedEmail = 'wibble') {
wp_send_json($passedEmail); // Returns '' when called via ajax
}
Unfortunately I can't use DOING_AJAX
to determine whether the field-check function should return
or wp_send_json
, because the form-check function itself is called via ajax, so DOING_AJAX
always returns true
.
I have half a dozen of these 'live check' functions for different field types, so I really don't want to duplicate them all. Is there any way for wp_ajax
to not send an empty parameter? Or a neater way of dealing with this?
It sounds similar to the issue that was raised in this old trac ticket, but it's not exactly the same, and that only discussed rolling it back between 3.4 & 3.5.