0

I have checkbox, that who is checked. That's will be inserted in my table:inclusion. I want to insert data, using checkbox with other textbox, but I don't have any idea for inserting data using checkbox, please help me out of this problem! Tyia!

Error: Invalid argument supplied for each()

Here's my code:

//script
 $(document).on('submit', '#user_form', function(event){
  event.preventDefault();
  var roomname = $('#text_name').val();
  var id = [];  
   $(':checkbox:checked').each(function(i){
    id[i] = $(this).val();
   });
  if(roomname != '')
  {
   $.ajax({
    url:"insert.php",
    method:'POST',
    data:new FormData(this),
    // data: {inclusion_name:inclusion_name},
    contentType:false,
    processData:false,
    success:function(data)
    {
     alert(data);
     $('#user_form')[0].reset();
     $('#userModal').modal('hide');
     dataTable.ajax.reload();
    }
   });
  }
  else
  {
   alert("Both Fields are Required");
  }
 });

insert.php

$statement = $connection->prepare("
   INSERT INTO rooms (roomname) 
   VALUES (:text_name)
  ");
  $result = $statement->execute(
   array(
    ':text_name' => $_POST["text_name"]
   )
  );

foreach($_POST["id"] as $id)
 {
  $statement = $connection->prepare("
   INSERT INTO inclusion (inclusion) 
   VALUES (:id)
  ");

  $result = $statement->execute(
   array(
    ':id' => $_POST["id"]
   )
  );
 }
3
  • Checkboxes are boolean values, meaning they're true or false. You'll probably want to insert into a MySQL TINYINT. It might be worth including a little snippet of the code for the checkbox so that people can help you better :) Commented Aug 13, 2018 at 7:45
  • how can I create a snippet? @Will Commented Aug 13, 2018 at 7:46
  • Copy paste the HTML code from your checkbox and format it like you have the others :) Commented Aug 13, 2018 at 7:46

1 Answer 1

1

When a checkbox isn't checked, it will not send a thing. it won't exist as far as php is concerned.

With checkboxes you will want to have a "backup" value by use of a hidden form filed with the same name as the checkbox.

<input type="hidden" name="something_checkbox" value="0">
<input type="checkbox" name="something_checkbox">

If the checkbox is checked a 1 will be sent. If the checkbox is unchecked a 0 will be sent by the "default" value provided by the hidden form.

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

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.