The usual practice here is to create a separate PHP file that outputs JSON data and fetch that data using an AJAX request. Below is an example of including JSON data inline, but I wouldn't typically recommend doing it like this, especially if the data is quite large.
Use json_encode()
to convert a PHP variable into something that can be used in JavaScript. With an associative array, you'll get a JavaScript object like {"a":1,"b":2,"c":3,"d":4,"e":5}
. With a non-associatve array, you'll get a JavaScript array like [1,2,3,4,5]
.
<script>
<?php
$tasks = array(
145 => array(
'name' => 'Sorting Task',
'owner' => 'user1'
),
2343 => array(
'name' => 'Processing Task',
'owner' => 'user2'
),
7266 => array(
'name' => 'Another Task',
'owner' => 'user1'
),
8373 => array(
'name' => 'Lorem Ipsum Task',
'owner' => 'user3'
)
);
echo 'display_diagram(' . json_encode($tasks) . ')';
?>
function display_diagram(tasks) {
$.each(tasks, function (id, task) {
console.log('Task #' + id + ': name=' + task.name + ', owner=' + task.owner);
});
}
</script>
The JavaScript above uses jQuery to process the object. It should output the following in the JavaScript console:
Task #145: name=Sorting Task, owner=user1
Task #2343: name=Processing Task, owner=user2
Task #7266: name=Another Task, owner=user1
Task #8373: name=Lorem Ipsum Task, owner=user3