简体   繁体   中英

How to pass different variables to jQuery function from php

I have a jQuery function to print charts (jqPlot framework). I want to print several charts with different options. So I need to call this function more than once and with different values.

I have an ugly solution like this:

//----- index.php:

// chart 1
$values = "[1,2,3]";
$id_chart = "chart1";
$options = "{...}";
include 'chart.php';

// chart 2
$values = "[8,2,5]";
$id_chart = "chart2";
$options = "{...}";
include 'chart.php';


//---- chart.php

 <script>
 $(function () { 
     $.jqplot(<?php echo $id_chart;?>, <?php echo $values;?>, <?php echo $options;?>);
 });
</script>

I tried another solution - call javascript function with variables and invocate jQuery function in JS function.

//---- index.php:

<script>
function printChart(opt1,opt2,opt3){
    $(function () { 
       $.jqplot(opt1, opt2, opt3);
    });
}
</script>

<?php
// chart 1
    $values = "[1,2,3]";
    $id_chart = "chart1";
    $options = "{...}";

    echo "<script>
    printChart(\"$id_chart\",\"$values\",\"$otpions\");
    </script>";

// chart 2
    $values = "[8,2,5]";
    $id_chart = "chart2";
    $options = "{...}";

    echo "<script>
    printChart(\"$id_chart\",\"$values\",\"$otpions\");
    </script>";
?>

But off course, jQuery can not 'see' variables from JS. Is it possible to pass the variables from JS to jQuery?

Do you have, please, any other suggestions for an optimal solution?

Thank you guys.

What you need to understand is that PHP is a server side language and JavaScript is a client side language. The PHP will completely execute, generating an HTML page (containing JavaScript) and then send that to the client's browser. The browser renders the HTML and executes the JavaScript. So what you need to do is print the information for JavaScript to the page. This should suffice:

<?php // your PHP to generate the values into an array
    $charts = [
        [
            'values' => [1,2,3]
            'id_chart' => 'chart1',
            'options' => '{...}'
        ],
        [
            'values' => [4,5,6]
            'id_chart' => 'chart2',
            'options' => '{...}'
        ]
    ];
?>
<script>
    var charts = JSON.parse(<?= json_encode($charts) ?>);
    $.each(charts, function () {
        $.jqplot(this.id_chart, this.values, this.options)
    });
</script>

Is it possible to pass the variables from JS to jQuery?

jQuery is a library for javascript.
this means that jQuery variables are javascript variables.
which means you can use them like any other javascript variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM