0

I'm trying to get checkbox values and store them in my database. I was following this https://stackoverflow.com/a/29948042/13695248 answer but I always get value 1 in my database, even if it's not checked. I've checked the network tab and it says 'on' for all my checkboxes. This is how one of them look like:

<div class="form-check">
    <input type="checkbox" class="form-check-input" id="front-disc-brake" name="front-disc-brake">
    <label class="form-check-label" for="front-disc-brake">Front disc brake</label>
</div>

I've tried two methods:

$front_disc_brake = $_POST['front-disc-brake'] ?? 0;

and:

$front_disc_brake = isset($_POST['front-disc-brake']) ? 1 : 0;

but as I said, it's always 1, doesn't matter if I check it or not.

randomdude
  • 267
  • 2
  • 11
  • Of course, yes. – randomdude Apr 08 '21 at 08:55
  • I assigned value="1" to it, but it always gives back '1', even if it's not checked. – randomdude Apr 08 '21 at 09:11
  • How are you submitting this form? Regular submission or through Javascript? – El_Vanja Apr 08 '21 at 09:19
  • It's through AJAX with the dropzone.js image uploader. – randomdude Apr 08 '21 at 09:20
  • 1
    Well, that makes a big difference, because the solution you've linked to refers to regular submissions (where a checkbox won't be present when not checked). You're obviously selecting all your form elements regardless of their state. You need to control this in JS. – El_Vanja Apr 08 '21 at 09:27
  • looks like you're right, I'm sending all the form data along with the files, but I'm not sure what to change there. Can I disturb you in private message? – randomdude Apr 08 '21 at 09:36
  • 1
    No, please don’t try to solicit “private” help from people here. Edit your question to include a proper [mre] of what you are doing, then everyone here can try to help you. – CBroe Apr 08 '21 at 11:12

2 Answers2

1

You need to assign a value to the checkbox for it to work.

For example:

Change

<input type="checkbox" class="form-check-input" id="front-disc-brake" name="front-disc-brake">

To

<input type="checkbox" class="form-check-input" id="front-disc-brake" name="front-disc-brake" value="1">

Then the isset() check will work as expected.

CloudTheWolf
  • 334
  • 2
  • 10
  • It gives 'front-disc-brake: 1' in the network tab instead of 'on', but it wasn't checked. So it should be 0. – randomdude Apr 08 '21 at 09:01
0

you must assign a value to the checkbox if you want it to work

<input type="checkbox" class="form-check-input" id="front-disc-brake" name="front-disc-brake" value="[just add value]">
TEST ME
  • 123
  • 2
  • 9