I have the following problem:
An html form that has N checkbox's used on a FormData to send a request through ajax with its information. On PHP, the $_POST['teste'] variable does not exists...
<form id="teste_form">
<input type="checkbox" name="teste[]">
<input type="checkbox" name="teste[]">
<input type="checkbox" name="teste[]">
<input type="checkbox" name="teste[]">...
</form>
<script>
var form_data_obj = new FormData( document.getElementById('teste_form') );
$.ajax({
...
data: form_data_obj
...
});
</script>
I know that I could use a "if(isset(...))" on PHP, but I really don't like that solution. To me, the best solution would be to send an empty array to PHP from the FormData object.
Obs: I tried somethings like, for example:
But without success... The result on PHP is respectively: ["undefined"], ["0"]
I wanted to get $ _POST ['test'] = [] in PHP
Is that possible?
Smells like this: How to Submit empty array from HTML Form Post to PHP
Workaround: You can use a hidden input element with an empty value on client side, and an empty value check on the server side. With something like this:
var appended = null;
$('.confirm_appointment').submit(function(e) {
if (appended !== null) appended.remove();
/************************************/
if ($("input[name='teste[]']:checked").length == 0) {
appended = $("<input type='hidden' name='teste[]' value=''>").appendTo($(this));
}
/************************************/
e.preventDefault();
$(this).append(decodeURIComponent($(this).serialize()) + '<br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='confirm_appointment' method='post' class='confirm_appointment'>
<input type='checkbox' name="teste[]" value='hello1' />
<input type='checkbox' name="teste[]" value='hello2' />
<input type='checkbox' name="teste[]" value='hello3' />
<input type='checkbox' name="teste[]" value='hello4' />
<input type='submit' class='update_appointment_button' value='submit' /><br />
</form>
And on PHP side:
$teste = array_filter($_POST["teste"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With