matt.crawfoord matt.crawfoord - 4 months ago 15
jQuery Question

how to pass php variable to jquery

i try to pass php variable to jquery ,i have try to use


But it's not working success, when i try to use

dataSource:
insted

dataSource: [
{ childName: "Child1", childId: 1, parentId: 1 },
{ childName: "Child2", childId: 2, parentId: 2 },
{ childName: "Child3", childId: 3, parentId: 1 },
{ childName: "Child4", childId: 4, parentId: 2 }
]


it's cannot show the second select ,but i find the $data is the same as the original data

my code ,

<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>

<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.607/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.607/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.607/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.607/styles/kendo.mobile.all.min.css"/>

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.2.607/js/kendo.all.min.js">
</script>
</head>
<body>

<input id="parent" />
<input id="child" />
<?php
$data = '[
{ childName: "Child1", childId: 1, parentId: 1 },
{ childName: "Child2", childId: 2, parentId: 2 },
{ childName: "Child3", childId: 3, parentId: 1 },
{ childName: "Child4", childId: 4, parentId: 2 }
]';
?>
<script>
$("#parent").kendoDropDownList({
dataTextField: "parentName",
dataValueField: "parentId",
dataSource: [
{ parentName: "Parent1", parentId: 1 },
{ parentName: "Parent2", parentId: 2 }
]
});

$("#child").kendoDropDownList({
cascadeFrom: "parent",
dataTextField: "childName",
dataValueField: "childId",

dataSource: <?php json_encode($data); ?>
});
</script>

</body>
</html>


i don't know what's problem with my code,please help me to solve the problem , anyhelp will be appreciated ! thanks!

Answer

You forget to echo your php variable

<?php echo json_encode($data); ?>

plus, since you want it in json format, you have to parse it too and because of that you have to enclose your property name in double quotes.

your php variable will become:

$data = '[
    { "childName": "Child1", "childId": 1, "parentId": 1 },
    { "childName": "Child2", "childId": 2, "parentId": 2 },
    { "childName": "Child3", "childId": 3, "parentId": 1 },
    { "childName": "Child4", "childId": 4, "parentId": 2 }
]';

and dataSource will be:

dataSource: JSON.parse(<?php echo json_encode($data); ?>)

Its working :)

 Its working :)

Comments