perkes456 perkes456 - 1 year ago 48
jQuery Question

Sending an array to PHP function from javascript and reading its values

I have a onclick and post function in jQuery where I pass two variables to my PHP function.

The functions look like following:

// alert("Button save pressed");
$.post('/user/AddRemoveBrandUsers', { brands: JSON.stringify(checkbox_events),userId:user_id} , function(data) {
alert("No changes were made.")
else {
if (data == "ok") {


The first value is an array in following format:

console.log(checkbox_events) gives a following output:

[2: "checked", 4: "checked", 5: "checked"]

I do `JSON.stringify(checkbox_events) to turn my array into JSON format and pass it to my PHP function like following:

public function AddRemoveBrandUsersAction()
$brands = $this->getRequest()->getPost("brands");
$userId = $this->getRequest()->getPost("userId");
// how can I now access each value of the brands array
// I need both key and value... How do I access them ??

Answer Source

use the code follows:

 if(!empty($brands) && sizeof($brands) > 0){
     foreach($brands as $key => $value){