Malintha
Malintha

Reputation: 4766

Call Javascript function with parameters inside PHP

I have a javascript function which has some parameters (an array). I want to call it inside php. Following is my code

 <script type="text/javascript">

<?php 

$task_list=array();
        foreach($tasks as $row2){


            $task_list=$row2;
        }

         echo "display_diagram(".$task_list.");";

        ?>

function display_diagram(var1){

     .........................
     .........................

 }

When I call it without any parameter it is working (I could displayed the content in javascript function. But when I give the parameter( it is an array it dose not working. Could you give this a solution?

Upvotes: 1

Views: 830

Answers (1)

quietmint
quietmint

Reputation: 14153

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

Upvotes: 4

Related Questions