I am trying to pass values of selected checkboxes to a PHP file using jQuery’s .getJSON method.
Problem: The values does not seem to be received by the PHP file. I am using print_f to see if the PHP file has received the form data. Looking at the return data, the error PHP throws [Undefined index:] tell me that the 2 arrays $bedroom and $bathroom are not defined. How do I get this to work?
HTML Code
<form action="form_ajax.php" method="post">
<input type="checkbox" name="bedroom[]" value="1">
<input type="checkbox" name="bedroom[]" value="2">
<input type="checkbox" name="bedroom[]" value="3">
<input type="checkbox" name="bathroom[]" value="1">
<input type="checkbox" name="bathroom[]" value="2">
<input type="checkbox" name="bathroom[]" value="3">
<input type="submit" id="button" value="submit!!!">
</form>
jQuery Code
$(function() {
$("#button").click(function(e) {
e.preventDefault();
var other_data = "hello";
$.getJSON("form.php", {some-other-data: other_data, bedroom: bedroom[], bathroom: bathroom[]}, function(data) {
console.log(data);
});
});
});
PHP Code
<?php
$bedroom = $_GET['bedroom'];
$bathroom = $_GET['bathroom'];
print_r($bedroom);
print_r($bathroom);
?>
According to the jQuery documentation of
$.getJSON()the data is passed as querystring variables, so I would suggest you try to use$_GETinstead:Edit, how to send all form-data to the php-file:
If you add an id attribute to the form-tag, you can easily use jQuery to serialize the form, like this, and pass that as the data object in
$.getJSON():Then all your selected checkboxes should be passed along to the PHP-file.