ron tornambe ron tornambe - 5 months ago 10
PHP Question

Why isn't PHP receiving an array of values?

I am passing multiple values to PHP with the same name using ajax. But when I dump the array, only the last value is shown.

The serialized form:


genres=59&genres=13&genres=15&genres=14&genres=16&genres=17&genres=18&genres=19&genres=20&genres=21&genres=22&genres=23&genres=24&accepted-media=1&special-instructions=&g-recaptcha-response=&userid=62&action=search


**PHP*

"genres=" . var_dump(array($_REQUEST["genres"])) . "\n";



array (size=1)

0 => string '24' (length=2)


JavaScript

$("#form-enablers").on("submit", function () {
$("#userid").val(localStorage.getItem("account-id"));
var data = $("#form-enablers").serialize() + "&action=search";
console.log(data);
ajax('post', 'php/enablers.php', data, success, "Error searching: ");
function success(table) {
console.log(table);
$('#table-list').empty().append(table);
$("#writers-list").css({ "display": "block" });
}
});

Answer

If you want to pass an array of values in a request, a special syntax is required. You need to add brackets [] to attribute name in order to put all attributes in an array.

In your case the serialized data should look like the following:

genres[]=59&genres[]=13&genres[]=15&genres[]=14&genres[]=16&genres[]=17&genres[]=18&genres[]=19&genres[]=20&genres[]=21&genres[]=22&genres[]=23&genres[]=24&accepted-media=1&special-instructions=&g-recaptcha-response=&userid=62&action=search

This way $_REQUEST['genres'] will contain an array of values instead of a single value.

Comments