0

In my html form all data is successfully validation except checkbox value. It's not validate with jquery/ajax request.

here is my html form ajax and html code (only terms part):

<tr>
<td>Terms & Conditions</td>
<td><input type="checkbox" name="terms"/>&nbsp; I agree to your <a href="">terms and 
conditions</a>.</td>

<script>
  $('#form1').submit(function(event) {
  event.preventDefault();
  $.ajax({
   type: 'POST',
   url: 'regProcess.php',
   data: $(this).serialize(),
   dataType: 'json',   
   success: function (data) {
        $('#info1').html('');
        $.each( data, function( key, value ) {

          $('#info1').append('<p>'+value+'</p>');
        });    

   }
  });
 });
</script>

In regProcess.php page following is my Checkbox validation code but it's not validating..

if(isset($_POST['terms']) && $_POST['terms'] == ""){
    $msg[] = "You must agree our terms and conditions";
    $msg1['error'] = true;
    }
Babu
  • 455
  • 2
  • 14
  • 33
  • see this http://stackoverflow.com/questions/11424037/does-input-type-checkbox-only-post-data-if-its-checked – Midhun KM Apr 11 '14 at 17:29
  • here you may get an answer: http://stackoverflow.com/questions/19893927/send-checkbox-value-in-php-form – Midhun KM Apr 11 '14 at 17:30

2 Answers2

1

Give check box a ID

<tr>
<td>Terms & Conditions</td>
<td><input type="checkbox" id="terms" name="terms"/>&nbsp; I agree to your <a href="">terms and 
conditions</a>.</td>

Then use this to find out checkbox is checked or not??

<script>
  $('#form1').submit(function(event) {
  event.preventDefault();
  if($('#terms').is(':checked') )
  {

  $.ajax({
   type: 'POST',
   url: 'regProcess.php',
   data: $(this).serialize(),
   dataType: 'json',   
   success: function (data) {
        $('#info1').html('');
        $.each( data, function( key, value ) {

          $('#info1').append('<p>'+value+'</p>');
        });    

   }
  });
  }
else{
alert("Check terms and condition");
}
 });
</script>

Live Example

Manwal
  • 23,450
  • 12
  • 63
  • 93
0

$_POST['terms'] will not be set if it's an unchecked checkbox. It should instead be:

if (empty($_POST['terms']) || $_POST['terms'] !== 'on') {

or just

if (empty($_POST['terms'])) {
Brian Adams
  • 1,080
  • 8
  • 9
  • The reason your php script isn't returning an error is because you are checking to see if `$_POST['terms']` is set, it is not. See my updated answer. – Brian Adams Apr 11 '14 at 17:37
  • Oh great you answer is working. but I don't understand why you use `on` ? – Babu Apr 11 '14 at 17:40
  • You could probably leave that out and just use `if (empty($_POST['terms'])) {` but web browsers will send the string 'on' as the value of a checked checkbox if you don't specify your own value. – Brian Adams Apr 11 '14 at 17:54