perkes456 perkes456 - 5 months ago 12
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:

$(".pop-save-us").click(function(){
console.log(checkbox_events);
console.log(user_id);
// alert("Button save pressed");
$.post('/user/AddRemoveBrandUsers', { brands: JSON.stringify(checkbox_events),userId:user_id} , function(data) {
if(checkbox_events.length==0)
{
alert("No changes were made.")
}
else {
if (data == "ok") {
alert("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");
for($i=0;$i<count($brands);$i++)
{
// how can I now access each value of the brands array
// I need both key and value... How do I access them ??
}
die("ok");
}

Answer

use the code follows:

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