views:

158

answers:

2

On my client side I'm sending an ajax request with jQuery in the following matter:

$.post(script.php, { "var1":"something", "var2":"[1,2,3]" }, function(data) { }, "json");

On the server side, in the CodeIgniter's controller I'm receiving the values like so:

$var1 = trim($this->input->post('var1'));
$var2 = trim($this->input->post('var2'));

My question is how do I convert the string in $var2 into a PHP array. I tried using json_decode($var2, true) but it returns a null since "[1,2,3]" is not a legal JSON string by itself.

Also, if you believe there is a better way for me to read the values on the server-side please show me how.

Thank you.

+1  A: 

You could do this:

$var2 = trim($this->input->post('var2'), "[]");

$array = explode(",", $var2);
bschaeffer
I thought about that, but I prefer not to. Today it's a simple array, tomorrow a more complex structure of array of arrays, etc.
thedp
+2  A: 

As @Galen stated in his comment to my question, it works. The reason I got a null from json_decode is because it tried it with a non-array value, which requires a double ".

thedp