Reputation: 1768
I have an array that I'm trying to pass to a php file which is passing, but it shows the array as a string. How do I convert the string to an array so I can go through it in php? Here's my code:
jQuery
$('#add-child').click(function()
{
var _attributes = [];
$('#attributes input').each(function()
{
_attributes.push($(this).val());
});
$.post('../assets/hub.php',{'task':'add-child','parent':$('#parent-id').val(),'value':$('#child-value').val(),'attributes':JSON.stringify(_attributes)},function(callback)
{
console.log(callback);
});
});
PHP
case 'add-child':
$department = $_POST['parent'];
$category = $_POST['value'];
$attributes = $_POST['attributes'];
print($department.' : '.$category.' : '.$attributes);
break;
CURRENT OUTPUT
test1 : test2 : ["sdfg","34","vsdf"]
** EDIT **
I removed JSON.stringify()
and added var_dump()
and this is the output:
string(3) "114"
string(4) "asdf"
array(3) {
[0]=>
string(4) "asdf"
[1]=>
string(4) "ZVCX"
[2]=>
string(5) "asdfr"
}
Upvotes: 2
Views: 341
Reputation: 10880
$attributes = json_decode($_POST['attributes']);
if you want to join the array back agian with a comma then
$attributes = implode(',' , json_decode($_POST['attributes']));
Upvotes: 1
Reputation: 254916
You don't need JSON.stringify
at all and you check that everything is passed successfully using
var_dump($department, $category, $attributes);
not the pring_r
with concatenations
Upvotes: 1