0

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" });
    }
});
ron tornambe
  • 10,452
  • 7
  • 33
  • 60

2 Answers2

2

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.

jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
0

Click here, is similar to your question though is not in Ajax

The main point is the name of the values need to have square brackets [] .

Community
  • 1
  • 1
Shing Kae
  • 11
  • 2