0

Sounds simple enough, but I just cannot make it work. I am trying to insert a checkbox value to database. If it checked, insert Y, if not, insert N. In my DOM, I see that the value of checkbox is changing to N after I click it, but the values are not changed in database. Maybe it is something small and stupid that I am missing.

So the default value is N.

Here's the HTML:

<div class="funkyradio">
    <div class="funkyradio-success">
       <input type="checkbox" name="animalCare" id="animalCare" value="N"/>
     <label for="animalCare">Hoolitsen loomade eest:</label>
     </div>
</div>

JS

//I have a lot more of those checkboxes
        $('#cleaningOk, #animalCare, #homeSchooling, #worktime_lenght, #sickChildren, #isSmoking, #isTattoo, #animalsOk, #disabledChildren, #singleParent, #driversLicense, #babyOk').change(function(){
            if ($(this).is(':checked')) {
                $(this).val('Y');
            } else {
                $(this).val('N');
            }
        });

For inserting I use formValidation.io plugin and if the checkbox is changed, I don't even see the N in formdata under the network tab, else I see the Y.

.on('success.form.fv', function(e, data) {
            // Prevent form submission
            e.preventDefault();
            console.log("validated");

            var $form = $(e.target),
                formData = new FormData(),
                params = $form.serializeArray(),
                files = $form.find('[name="userProfilePhoto"]')[0].files;
            $.ajax({
                url: $form.attr('action'),
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data) {},
                error: function(jqXHR, textStatus, errorThrown, data) {
                    console.log(jqXHR, textStatus, errorThrown, data);
                }
            });
});

PHP

    ////SERVICES
    if (isset($_POST["cleaningOk"], $_POST['animalCare'], $_POST['homeSchooling'])){
        $cleaningOk = $_POST['cleaningOk'];
        $animalCare = $_POST['animalCare'];
        $homeSchooling = $_POST['homeSchooling'];

        $nanny_services = $user_home->runQuery("INSERT into services (user_id, koristab, loomade_hoolitsus, koduõpetamine) VALUES (:user_id, :cleaningOk,  :animalCare, :homeSchooling) ON DUPLICATE KEY UPDATE koristab= VALUES(koristab), loomade_hoolitsus= VALUES(loomade_hoolitsus), koduõpetamine=VALUES(koduõpetamine)");
        $nanny_services->bindparam(':cleaningOk', $cleaningOk, PDO::PARAM_STR);
        $nanny_services->bindparam(':animalCare', $animalCare, PDO::PARAM_STR);
        $nanny_services->bindparam(':homeSchooling', $homeSchooling, PDO::PARAM_STR);
        $nanny_services->bindparam(':user_id', $user_id, PDO::PARAM_STR);

        $nanny_services->execute();
        $response_array["status"] = 'success';
    }
    ////SERVICES
3
  • Check for errors on your query execution. koristab= VALUES(koristab), loomade_hoolitsus= VALUES(loomade_hoolitsus) should throw something. Also why update to the same value? Commented Jun 7, 2016 at 13:06
  • what do you have in var_dump($_POST)? Commented Jun 7, 2016 at 13:06
  • Checkboxes are not sent to the server when they are not checked and that is probably why they are not included in FormData either. Commented Jun 7, 2016 at 13:08

2 Answers 2

2

Don't try to change the value on the client. Checkboxes are not designed to work that way. If the checkbox isn't checked, it won't appear in the submitted data.

Test if the data is sent instead.

$value = "N";
if (isset($_POST['animalCare'])) {
    $value="Y";
}

(Obviously, don't make the value being sent from the client a requirement of the query to be run at all).

Sign up to request clarification or add additional context in comments.

5 Comments

@raqulka — Since you said you could see the Y in the submitted data, that suggests that something else has broken.
What do you mean by: don't make the value being sent from the client a requirement of the query to be run at all?
One more weird thing, Now I see N in formData, but it still inserts Y
@raqulka — On line 2 of the PHP in the question, you have an if statement which doesn't run the query if no animalCare is included in the form data. Don't do that.
@raqulka — The value in the form data doesn't matter. The presence of any value indicates that the checkbox has been checked and so is a "Yes" result. The code in the answer never looks at the value of $_POST['animalCare'], only if it is set.
0

This is because the function serializeArray won't take unchecked checkboxes.

This is the default behavior of HTML Forms.

From jquery.com:

The .serializeArray() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.

function testForm() {
  console.log($("#myForm").serializeArray());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
  <input type="checkbox" name="checked" value="T" checked>
  <input type="checkbox" name="unchecked" value="F">
  <a href="#" onclick="testForm()">Submit</a>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.