-1

I posted a smaller to this yesterday and was shown how to do this but it doesn't work and the user never got back to me and I have been working on the same problem for hours.

I am trying to post a checkbox array from jQuery to php, when I run my code nothing seems to happen and when I try var_dump($_POST) this is all I get

Beck
  • 9
  • 5

2 Answers2

-1

Using this question as a reference, it seems that jQuery doesn't handle arrays too well. You can use to snippet from the accepted answer and it should work just fine.

serialize().replace(/%5B%5D/g, '[]')
Community
  • 1
  • 1
Maciej Wilczyński
  • 379
  • 1
  • 5
  • 13
-1
  • Change the submit to a button or better use the form's submit event
  • why data-type html?
  • Your php does not seem to react to the serialised data but returns a button...

try my code here: http://plungjan.name/SO/sport.php

I am not unravelling the check box array - that is up to you

<?PHP
if (isset($_POST['saved'])) {
  echo "saved"; exit(0);
}
else if (isset($_POST['Submit'])) {
  echo var_dump($_POST["sport"]); exit(0);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Sports quiz</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
  $('#myForm').on("submit", function(ev) {
    ev.preventDefault(); // cancel submit
    var $form = $(this);
    if ($("[type=checkbox]:checked").length ==0) {
      alert("Please check one or more");
      return false;
    }
    var formData = $form.serializeArray();
    formData.push({name:"Submit",value:"submit"}); // note I changed the name from submit to Submit
    $.post('sport.php',formData, function(data) {
      console.log("Data",data);
      if (confirm('You want to save \n' + data + ' as your sport?')) {
        formData = $form.serializeArray();
        formData.push({name:"saved",value:"saved"});
        $.post('sport.php',formData,function(data) {
          console.log("Saved Data",data);
        });
      }
    });
  });
});
</script>
</head>
<body>


<form id="myForm">
  <input type="checkbox" name="sport[]" value="Football">Football<br>
  <input type="checkbox" name="sport[]" value="Rugby">Rugby<br>
  <input type="checkbox" name="sport[]" value="Golf">Golf<br>
  <input type="checkbox" name="sport[]" value="Basketball">Basketball<br>
  <br> <input type="submit" class="btn btn-info" name="Submit" value="submit">
</form>
</body>
</html>
mplungjan
  • 169,008
  • 28
  • 173
  • 236