I am having trouble creating correct format of JSON to pass it to js from php.
I am using extjs
and in my tree
, I need to add children
:
var treePanel = Ext.create('Ext.tree.Panel',
{
id: 'tree-panel',
region: 'north',
split: true,
height: '50%',
minSize: 150,
rootVisible: false,
autoScroll: true,
store: store,
listeners: {// more code here}
});
Now I need to assign the create store
variable:
var store = Ext.create('Ext.data.TreeStore',
{
root:
{
expanded: false,
children: file_names
}
});
Now the problem appears when I have to create file_names
object from within php
tags.
file_names = [{text: 'google', leaf: true, icon: 'pic.png'}, {text: 'yahoo', leaf: true, icon: 'pic.png'}]
, then everything is finefile_names
's content from within php, then I am starting to experience issuesThis is how I am trying to create file_name from php:
var store = Ext.create('Ext.data.TreeStore',
{
root:
{
expanded: false,
children: [
<?php
$name = empty($_GET['name']) ? false : $_GET['name'];
$files = empty($_GET['files']) ? false : $_GET['files'];
if ($name)
{
// $files_arr = explode(',', $files);
$file_arr = array('text'=>$files_arr[0], 'leaf'=>true, 'icon'=>'images/xml.png');
//echo stripslashes(json_encode($file_arr));
echo json_encode($file_arr );
}
?>
]
}
};
Try this way:
<?php
$name = empty($_GET['name']) ? false : $_GET['name'];
$files = empty($_GET['files']) ? false : $_GET['files'];
if ($name)
{
$files_arr = explode(',', $files);
foreach ($files_arr as $value)
{
$file_arr[] = array(
'text' => $value,
'leaf' => true,
'icon' => 'images/xml.png'
);
}
}
$var = json_encode($file_arr);
echo $var;
Test:
http://localhost/test.php?name=test&files=google,yahoo
Give us:
'[{"text":"google","leaf":true,"icon":"images\\/xml.png"},{"text":" yahoo","leaf":true,"icon":"images\\/xml.png"}]'
And to output do it like this:
root:
{
expanded: false,
children: <?php echo $var; ?>
}
ie: remove [' and '], json_encode takes care of all needed to properly format javascript code.