[英]Using jQuery AJAX to pass checkbox data
I am trying to pass values of selected checkboxes to a PHP file using jQuery's .getJSON
method. 我正在尝试使用jQuery的
.getJSON
方法将选定复选框的值传递给PHP文件。
Problem: The values does not seem to be received by the PHP file. 问题: PHP文件似乎未接收到这些值。 I am using
print_f
to see if the PHP file has received the form data. 我正在使用
print_f
来查看PHP文件是否已收到表单数据。 Looking at the return data, the error PHP throws [ Undefined index:
] tell me that the 2 arrays $bedroom
and $bathroom
are not defined. 查看返回数据,错误PHP引发[
Undefined index:
],告诉我Undefined index:
2个数组$bedroom
和$bathroom
。 How do I get this to work? 我该如何工作?
HTML Code HTML代码
<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 jQuery代码
$(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代码
<?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 $_GET
instead: 根据
$.getJSON()
的jQuery文档,数据作为查询字符串变量传递,因此我建议您尝试使用$_GET
代替:
$bedroom = $_GET['bedroom'];
$bathroom = $_GET['bathroom'];
Edit, how to send all form-data to the php-file: 编辑,如何将所有表单数据发送到php文件:
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()
: 如果您向表单标签添加id属性,则可以轻松地使用jQuery这样序列化表单,并将其作为
$.getJSON()
的数据对象传递:
$.getJSON("form.php", $("#your-form-id").serialize());
Then all your selected checkboxes should be passed along to the PHP-file. 然后,所有选中的复选框应传递到PHP文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.