Answer the question
In order to leave comments, you need to log in
$_POST accepts NULL on AJAX request and prevents using PDO, how to fix?
There is a form
<form id="filter">
<input type="checkbox" name="day[]" value="1">
<input type="checkbox" name="day[]" value="2">
<input type="checkbox" name="day[]" value="3">
</form>
var a = 0;
var b = 5;
var c = $( "#filter" ).serialize();
var Data = 'a=' + a + '&' + 'b=' + b + '&' + c;
var process = false;
$.ajax({
url: 'script.php',
method: 'POST',
data: Data,
beforeSend: function() {
process = true;
}
});
$a = $_POST['a'];
$b = $_POST['b'];
$c = implode(',', $_POST['day']); // Warning: implode(): Invalid arguments passed
$in = str_repeat('?,', count($c) - 1) . '?'; // Warning: Second argument has to be greater than or equal to 0
$sql = "SELECT * FROM table WHERE day IN ($in) ASC LIMIT :a, :b";
$stmt = $pdo->prepare($sql);
$stmt->execute($с, [$a, $b]);
$data = $stmt->fetchAll();
echo json_encode($data);
if (isset($_POST['day'])) {
$c = implode(',', $_POST['day']);
}
Answer the question
In order to leave comments, you need to log in
If you have NOT checked a single check-box, then you will not receive anything.
Those. if you submit the form from my example, $_POST will be:
array(2) {
["a"]=>
string(1) "0"
["b"]=>
string(1) "5"
}
$result = [];
$a = (int) $_POST['a'];
$b = (int) $_POST['b'];
$c = array_filter( (array) $_POST['day'] );
if ( !empty($c) )
{
$c = implode(',', $_POST['day']);
$in = str_repeat('?,', count($c) - 1) . '?';
$sql = "SELECT * FROM table WHERE day IN ($in) ASC LIMIT :a, :b";
$stmt = $pdo->prepare($sql);
$stmt->execute($с, [$a, $b]);
$data = $stmt->fetchAll();
$result = $data;
}
echo json_encode($result);
<form id="filter">
<input type='hidden' name='a' value='0' />
<input type='hidden' name='b' value='5' />
<input type="checkbox" name="day[]" value="1">
<input type="checkbox" name="day[]" value="2">
<input type="checkbox" name="day[]" value="3">
</form>
$.ajax({
url: 'index.php',
method: 'POST',
data: $("#filter").serialize()
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question