My goal is that when any checkbox is unchecked/checked in a form, the checkbox values will be sent automatically to a PHP file to filter an SQL database and update a certain part of the HTML page (without reloading the page). The steps:
- Check when form is submitted in JavaScript.
- Prevent page from loading.
- Use serializeArray on form data.
- Convert data to JSON string.
- Pass to php file through ajax.
- php file will echo out the data passed. (for debugging)
My problems:
- Data passed through ajax is empty. Nothing passes even though data is successfully converted to JSON string. Or it gives a parse error.
- Since my form already creates arrays from POST data, I am unsure if serializeArray is necessary. If not, how would I pass the data?
The following is a snippet of my HTML code with some PHP that pulls in data from a MySQL database.
<form id="selectors" method="POST">
<div class="selector-title">Categories</div>
<?php foreach ($categories as $category): ?>
<input type='checkbox' name='category[]' value='<?php echo $category['category_id'] ?>' id='selector1'><i class="fas fa-<?php echo $category['category_icon'] ?>"></i> <?php echo $category['category_title'] ?>
<?php endforeach ?>
<div class="selector-title">Age</div>
<?php foreach ($ages as $age): ?>
<input type='checkbox' name='age[]' value='<?php echo $age['age_id'] ?>' id='selector2'><i class="fas fa-<?php echo $age['age_icon'] ?>"></i> <?php echo $age['age_range'] ?>
<?php endforeach ?>
<input type="submit">
</form>
<?php getGiftsInCategories(); ?>
This is my Javascript code that is under the footer in the HTML body:
$(document).ready(function(){
$("form").on("submit", function(e){
e.preventDefault();
alert("Page prevented from loading. In function.")
var data = $('form').serializeArray(); //necessary? if $_POST is already in an array?
var JSONData = JSON.stringify(data); //convert array to string
alert(JSONData);
var type = typeof JSONData;
alert(type);
$.ajax({
url: "includes/ajax_functions.php",
type: "POST",
async: true,
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: {data : JSONData},
success: function(data){
alert(data);
console.log("success");
},
error: function (request, status, error) {
console.log(status);
console.log(request.responseText);
console.log(error);
}
});
});
})
And my ajax_functions.php:
<?php
function getGiftsInCategories() {
echo $data = json_decode($_POST['data']);
}
?>
When checking the console and alerts in Chrome, after JSON.stringify, I get this alert:
[{"name":"category[]","value":"4"},{"name":"age[]","value":"3"},{"name":"age[]","value":"4"}]
which corresponds with the checkboxes I selected.
However, $.ajax fails and I get this error:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at n.parseJSON (jquery.min.js:4)
at vc (jquery.min.js:4)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
If I remove dataType: 'json'
, I get success in the console.log, but my alert is blank, so no data has passed. I also get
Notice: Undefined index: data in ...\includes\ajax_functions.php