canodiug
canodiug

Reputation: 3

Solution for checking the checkboxes with php. Think I must use a value

How should I define the if isset? If I write it as follows, the php does not perceive the click.

`if(!isset($_POST['checkbox1']) || !isset($_POST['checkbox2']) || !isset($_POST['checkbox'])   )
    {
        echo json_encode(array('info' => 'error', 'msg' => 'Füllen Sie bitte alle Felder aus.'));
    }`this?

The checkboxes query works offline, but not online. I think I have to work with a value. It should not be a selection, but all checkboxes must be selected to be able to send.

I can not find the right solution in PHP. The checkboxes are checked but not processed.

Can somebody help me with the php-code?

<form id="contact-form" action="#">

  <div class="row contact-row">
    <div class="col-md-6 col-sm-6 col-xs-6 contact-name">
      <input type="text" id="firstname" name="firstname" placeholder="Vorname" required>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6 contact-name">
      <input type="text" id="lastname" name="lastname" placeholder="Nachname" required>
    </div>
  </div>

  <div class="row contact-row">
    <div class="col-md-6 col-sm-6 col-xs-6 contact-name">
      <input name="telefon" id="telefon" type="text" placeholder="Telefon" required>
    </div>
    <div class="col-md-6 col-sm-6 col-xs-6 contact-email">
      <input name="email" id="email" type="email" placeholder="E-mail" required>
    </div>
  </div>

  <input name="subject" id="subject" type="text" placeholder="Anfrage">
  <textarea name="message" id="message" placeholder="Nachricht" rows="5"></textarea>

  <div class="col-md-12 col-sm-12 col-xs-12 mb-30">
    <h6>Your Choose</h6>
    <ul class="checkboxes">
      <li>
        <input type="checkbox" class="input-checkbox" name="checkbox1" id="checkbox1" required>
        <label for="checkbox1">*&nbsp;&nbsp;Red</label>
      </li>
      <li>
        <input type="checkbox" class="input-checkbox" name="checkbox2" id="checkbox2" required>
        <label for="checkbox2">*&nbsp;&nbsp;White </label>
      </li>
      <li>
        <input type="checkbox" class="input-checkbox" name="checkbox3" id="checkbox3" required>
        <label for="checkbox3">*&nbsp;&nbsp;Blue</label>
      </li>
    </ul>
  </div>

  <input type="submit" class="btn btn-lg btn-color btn-submit" value="Nachricht senden" id="submit-message">
  <div id="msg" class="message"></div>
</form>
<?php
if ($_POST) {

    $to = "abcd.de"; // email here
    $subject = 'Kontaktformular '; // Subject message here

}

//Send mail function
function send_mail($to, $subject, $message, $headers)
{
    if (@mail($to, $subject, $message, $headers)) {
        echo json_encode(array('info' => 'success', 'msg' => "Message send. "));
    } else {
        echo json_encode(array('info' => 'error', 'msg' => "Message not send."));
    }
}

//Check if $_POST vars are set
if (!isset($_POST['firstname']) || !isset($_POST['lastname']) || !isset($_POST['telefon']) || !isset($_POST['email']) || !isset($_POST['message'])) {
    echo json_encode(array('info' => 'error', 'msg' => 'Fill out all fields.'));
}


//Sanitize input data, remove all illegal characters    
$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
$lastname = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);

$telefon = filter_var($_POST['telefon'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

$website = filter_var($_POST['website'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);


//Validation
if ($firstname == '') {
    echo json_encode(array('info' => 'error', 'msg' => "Firstname please."));
    exit();
}
if ($lastname == '') {
    echo json_encode(array('info' => 'error', 'msg' => "Lastname please."));
    exit();
}

if ($telefon == '') {
    echo json_encode(array('info' => 'error', 'msg' => "Telefon?"));
    exit();
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(array('info' => 'error', 'msg' => "Valid e-mail."));
    exit();
}

if ($message == '') {
    echo json_encode(array('info' => 'error', 'msg' => "Message?"));
    exit();
}

if ($checkbox1 == '') {
    echo json_encode(array('info' => 'error', 'msg' => "choose 1."));
    exit();
}
if ($checkbox2 == '') {
    echo json_encode(array('info' => 'error', 'msg' => "choose 2."));
    exit();
}
if ($checkbox3 == '') {
    echo json_encode(array('info' => 'error', 'msg' => "choose 3."));
    exit();
}


//Send Mail
$headers = 'From: ' . $email . '' . "\r\n" .
    'Reply-To: ' . $email . '' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

send_mail($to, $subject, $message . "\r\n\n" . 'Vorname: ' . $firstname . "\r\n" . 'Nachname: ' . $lastname . "\r\n" . 'Telefon: ' . $telefon . "\r\n" . 'Email: ' . $email, $headers);
?>
(function($) {
  "use strict";
  var submitContact = $('#submit-message'),
    message = $('#msg');

  submitContact.on('click', function(e) {
    e.preventDefault();

    var $this = $(this);

    $.ajax({
      type: "POST",
      url: 'mail-send.php',
      dataType: 'json',
      cache: false,
      data: $('#contact-form').serialize(),
      success: function(data) {

        if (data.info !== 'error') {
          $this.parents('form').find('input[type=text],input[type=email],input[type=checkbox],textarea,select').filter(':visible').val('');
          message.hide().removeClass('success').removeClass('error').addClass('success').html(data.msg).fadeIn('slow').delay(5000).fadeOut('slow');
        } else {
          message.hide().removeClass('success').removeClass('error').addClass('error').html(data.msg).fadeIn('slow').delay(5000).fadeOut('slow');
        }
      }
    });
  });

});

Upvotes: 0

Views: 64

Answers (2)

Cemal
Cemal

Reputation: 1579

If the checkboxes are checked, $_POST will have it's values, otherwise it wont. To check if checkboxes are actually in checked state,

$checkbox1 = isset($_POST['checkbox1']) ? true : false;
$checkbox2 = isset($_POST['checkbox2']) ? true : false;
$checkbox3 = isset($_POST['checkbox3']) ? true : false;

alternatively, to get it's value, you can do

$checkbox1 = isset($_POST['checkbox1']) ? $_POST['checkbox1'] : false;
$checkbox2 = isset($_POST['checkbox2']) ? $_POST['checkbox2'] : false;
$checkbox3 = isset($_POST['checkbox3']) ? $_POST['checkbox3'] : false;

Below does same as above and more with PHP 7's null coalescing operator. The more side is, it also requires the value not to be null, to have it assigned to the variable.

$checkbox1 = $_POST['checkbox1'] ?? false;
$checkbox2 = $_POST['checkbox2'] ?? false;
$checkbox3 = $_POST['checkbox3'] ?? false;

and change your verifications to

if($checkbox1 == false) {
    echo json_encode(array('info' => 'error', 'msg' => "choose 1."));
    exit();
}
if($checkbox2 == false) {
    echo json_encode(array('info' => 'error', 'msg' => "choose 2."));
    exit();
}
if($checkbox3 == false) {
    echo json_encode(array('info' => 'error', 'msg' => "choose 3."));
    exit();
}

Upvotes: 1

Krzysztof Janiszewski
Krzysztof Janiszewski

Reputation: 3834

Problem

If checkbox is not selected it's value does not appear in php $_POST array.

Here is a handy article that might help you

Solution

Since we know that if a checkbox that's not selecetd does not appear in $_POST array we can just chek if of all of them are there. If not -> one of them is not checked.

if (!array_key_exists('checkbox1', $_POST) || !array_key_exists('checkbox2', $_POST) || !array_key_exists('checkbox3', $_POST)) {
    //One of checkboxes was not selected
}

Too long if condition? I agree.

Let's make a simple function

function array_keys_missing(array $keys, array $arr) {
    return array_flip(array_diff_key(array_flip($keys), $arr));
}

if ($missing = array_keys_missing(['checkbox1', 'checkbox2', 'checkbox3'], $_POST)) {
    switch (array_shift($missing)) {
        case 'checkbox1':
            echo json_encode(array('info' => 'error', 'msg' => "choose 1."));
            exit();
        break;
        case 'checkbox2':
            echo json_encode(array('info' => 'error', 'msg' => "choose 2."));
            exit();
        break;
        case 'checkbox3':
            echo json_encode(array('info' => 'error', 'msg' => "choose 3."));
            exit();
        break;
    }
}

Why is it a better solution than isset()?

isset() is a proper way to go, but it returns false if variable exists but has value null and that's why this solution is more errorproof.

Upvotes: 0

Related Questions