Use PHP's $_POST values in a JavaScript File

2020-07-28 00:04发布

I'm using Morris JS to display a Line Chart.

I have a JavaScript file with static values

$(function() {

  Morris.Line({
  element: 'morris-line-chart',

      data: 
    [
        { year: '2015', a: 20 },
        { year: '2016', a: 25 },
        { year: '2017', a: 40 },
    ],

    xkey: 'year',
    ykeys: ['a'],
    labels: ['Equity Partners ']

});

I was expecting I could do

$(function() {

  Morris.Line({
  element: 'morris-line-chart',

      data: 
    [
        { year: '2015', a: <?php echo $_POST["AmericanIndian_EP"];  ?> },
        { year: '2016', a: <?php echo $_POST["AmericanIndian_A"];  ?> },
        { year: '2017', a: <?php echo $_POST["AmericanIndian_C"];  ?> },
    ],

    xkey: 'year',
    ykeys: ['a'],
    labels: ['Equity Partners ']

});

to get the PHP values I have used PHP's POST on after submitting a form and display it on the JavaScript table data. But, it throws an error on my PHP input.

So basically, I would just like to know how I could input PHP in my JavaScript file?

2条回答
虎瘦雄心在
2楼-- · 2020-07-28 00:19

You can submit a form using javascript

$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(data){
        // data here should have the new values for your chart
        console.log('form submitted.');
      }
    });
    return false;
});
查看更多
冷血范
3楼-- · 2020-07-28 00:29

According to the expected data for Morris.Line, you need to use json_encode() to supply the entire object to javascript so that everything is automatically escaped for use by JS.

...
element: 'morris-line-chart',
data: <?php json_encode(
[
    ['year'=>'2015','a'=>$_POST["AmericanIndian_EP"]],
    ['year'=>'2016','a'=>$_POST["AmericanIndian_A"]],
    ['year'=>'2017','a'=>$_POST["AmericanIndian_C"]]
]
); ?>,
xkey: 'year',
...
查看更多
登录 后发表回答