user3784251
user3784251

Reputation: 520

seperate each array value from array passed by ajax -- php

I passed an array using Ajax and i echoed it in php , it works good. But i don't know how to separate its value and find its length.

Here is the code:

var myCheckboxes = new Array();
        $(".book_type:checked").each(function() {
           myCheckboxes.push($(this).val());
        });

            $.post("s.php?c="+category+"&k="+myCheckboxes,{data : "some data"}, function(response){
   $("#show_result").html(response);

And the php is:

$a=$_GET['k'];
echo $a;

it displays the values of all checkbox like this

all,0,1,2,3,4

How can i find $a length as array?. if i use sizeof($a) it shows as 1. Also how to separate those values into each single value. Any suggestion

Upvotes: 1

Views: 94

Answers (4)

Priyank
Priyank

Reputation: 3868

try like this

$a=$_GET['k'];
$value= explode(",",$a);
echo sizeof($value); //output 6
echo $value[0];      //all
echo $value[1];      //0
echo $value[2];      //1
echo $value[3];      //2
echo $value[4];      //3
echo $value[5];      //4

Upvotes: 1

Sachin Tyagi
Sachin Tyagi

Reputation: 86

Try using:

$a=$_GET['k'];
$a=explode(',', $a);
echo count($a);

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

You should call JSON.stringify in your javascript:

//                   ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓
... category+"&k=" + JSON.stringify(myCheckboxes) ...

or, alternatively, use jQuery ajax syntax sugar in your post request:

$.post("s.php", { k: myCheckboxes, ... });

This will provide a json as string passed to controller. From within your controller you should json_decode the received parameters:

$a = $_GET['k'];
print_r(json_decode($a));

Hope this helps.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388336

Pass the value as an array

$.post("s.php", {
    data: "some data",
    c: category,
    k: myCheckboxes
}, function (response) {
    $("#show_result").html(response);
})

then

$a=$_GET['k'];

where $a will be an array, so count($a) should give you the length

Upvotes: 0

Related Questions