jeudi 10 janvier 2019

Pass Checkbox Array into AJAX call

I'm trying to pass a checkbox array into an AJAX call for a search form im working on:

HTML:

<form id="searchForm">
    <input type="checkbox" class="typesSearch" name="types[]" value="Fundraiser" checked />&nbsp;Fundraiser<br>
    <input type="checkbox" class="typesSearch" name="types[]" value="Conference" checked />&nbsp;Conference<br>
</form>

JavaScript:

var types = [];

var eventTypes = document.forms['searchForm'].elements[ 'types[]' ];

for (var i=0, len=eventTypes.length; i<len; i++) {
    if (eventTypes[i].checked ) {
        types.push($(eventTypes[i]).val());
    }
}

$.ajax({
    url: "https://www.example.com/search.php",
    method: "post",
    data:{
        eventname: eventname,
        types: types
    },
    dataType:"text",
    success:function(data)
    {
        $('#eventsList').html(data);
        $('#eventsList').slick($opts);
    }
});

PHP:

$event_types = $_POST['types'];

The types array is fine on the javascript side, its when it hits the PHP side that $_POST['types'] is read as being empty.

Why is it that $_POST['types'] is read as empty? Is there something in the AJAX call where I need to define that I'm passing in an array instead of a string?




Aucun commentaire:

Enregistrer un commentaire