Search code examples
buttonliftgoogle-visualization

How to call a javascript function with Lift after clicking a button?


Here's my HTML code:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

  function drawChart() {
      var data = new google.visualization.DataTable();
      data.addColumn('string','Year');
      data.addColumn('number','D1');
      data.addColumn('number','D2');
      data.addRows(2);
      data.setValue(0,0,'1900');
      data.setValue(1,0,'1910');
      data.setValue(0,1,1);
      data.setValue(1,1,2);
      data.setValue(0,2,3);
      data.setValue(1,2,1);
      var options = {title: 'Tree Chart',
                     hAxis: {title: 'Time',  titleTextStyle: {color: 'red'}},
                     pointSize: 5};
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
  }

  function showChart(){  
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart);
  }

</script>
<form class="form-inline lift:form.ajax">
<div class="lift:DChart.render">
<button id="getChart" value="Get Chart" class="btn btn-inverse">Get Chart</button>
</div>
</form>
<div id="chart_div"></div>

the showChart() function displays the chart in chart_div

Here's my Lift code:

object DChart {
        def render = {
          def process():JsCmd = Run("showChart();")
          "#getChart"  #> SHtml.button("Get Chart", process)
        }
   }

Clicking on the button should execute the showChart() function.. sadly it doesn't work..

Please help me understand how to run the script function from lift!


Solution

  • SHtml.button takes as an argument () => Any so any JavaScript will not get returned to the browser and executed.

    I would do one of two things:

    1. Use SHtml.ajaxButton instead since the method body expects a JsCmd return
    2. Bind the event instead, like: "#getChart [onclick]" #> SHtml.onEvent((str) => process())

    Both do essentially the same thing and should get your code working. Option 1 will replace your entire HTML button with the one lift renders, Option 2 will just add the ajax to an onclick event on the existing HTML button.

    I assume you'll be doing something more complicated, and actually want to make an ajax call - but if you just want to add the showChart() call clientside, you can simply say: "#getChart [onclick]" #> process().toJsCmd