0

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:

  1. Check when form is submitted in JavaScript.
  2. Prevent page from loading.
  3. Use serializeArray on form data.
  4. Convert data to JSON string.
  5. Pass to php file through ajax.
  6. 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

1 Answer 1

0
contentType: "application/json; charset=utf-8",

PHP doesn't know how to decode JSON encoded HTTP requests…

data: {data : JSONData},

… but you're passing an object to data, not a string of JSON, so the content-type is a lie.

Remove the contentType line.


echo $data = json_decode($_POST['data']);

The results of decoding your JSONified array will be an array.

It won't be HTML (you haven't overriden the content type that PHP will be setting so you are claiming to be sending HTML) and it won't be JSON (the dataType property you set tells jQuery to ignore the content type and treat the response as JSON).

Output data in a sensible format.

1
  • I removed the contentType line and replaced echo $data.. line with print_r(json_decode(($_POST['data'])));. It still gives me a parsererror in the console and undefined index: data on HTML page.
    – ibkid
    Commented May 17, 2020 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.