I'm working on a theme that uses ajax for a custom frontend registration form. To this, I am trying to integrate a required checkbox for terms and conditions. However, I am pulling blanks when trying to get the value on whether the checkbox is checked or not. I'm sure it has something to do with how I am using ajax.
My checkbox with name and value set:
<input type="checkbox" name="agreement" value="1" id="agreement">I agree to Terms & Conditions.
I then assign my variables to my ajax form:
function ajax_register_form(){
check_ajax_referer( 'register_ajax_nonce','security-register');
$user_email = trim( $_POST['user_email_register'] ) ;
$user_name = trim( $_POST['user_login_register'] ) ;
//add checkbox requirement
$user_agreement = trim ( $_POST['agreement'] );
if (preg_match("/^[0-9A-Za-z_]+$/", $user_name) == 0) {
print __('Invalid username( *do not use special characters or spaces ) ','wptheme');
die();
}
Then I set a conditional for my requirement:
if( $user_agreement == '' ) {
print __('Please agree to the Terms & Conditions.','wptheme');
exit();
}
The email and username variables work fine. I thought I could just create a conditional that had a value if checked or no value if not checked. However, it always passes as having no value no matter what. I have also tried setting the input value to other things like 'agree" etc..
Any guidance would be helpful.
UPDATE
I think this is the part I am missed as I don't work with ajax a lot I was missing th jquery component. I need to register my variable for the checkbox here also, correct?
function wptheme_register (){
var user_login_register = $('#user_login_register').val();
var user_email_register = $('#user_email_register').val();
var nonce = $('#security-register').val();
var agreement = $('#agreement').val();
var ajaxurl = control_vars.admin_url+'admin-ajax.php';
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
'action' : 'ajax_register_form',
'user_login_register' : user_login_register,
'user_email_register' : user_email_register,
'security-register' : nonce,
'agreement' : agreement
},
<form></form>
also put<input type="checkbox" required>
and try by removingvalue="1"
also you can try like thisif($user_agreement == '0' )
, if checkbox not checked, it has value0
– Sheharyvar agreement = $('#agreement').val();
aftervar nonce
and indata
'security-register' : nonce, 'agreement' : agreement
– Shehary