0

I am new to Ajax and Json. I am trying to implement a Google Chart like in this example

 <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">

 google.charts.load('current', {packages: ['corechart', 'line']});
 google.charts.setOnLoadCallback(drawBasic);

function drawBasic() {

  var data = new google.visualization.DataTable();
  data.addColumn('number', 'X');
  data.addColumn('number', 'Dogs');

  data.addRows([
    [0, 0],   [1, 10],  [2, 23],  [3, 17],  [4, 18],  [5, 9],
    [6, 11],  [7, 27],  [8, 33],  [9, 40],  [10, 32], [11, 35],
    [12, 30], [13, 40], [14, 42], [15, 47], [16, 44], [17, 48],
    [18, 52], [19, 54], [20, 42], [21, 55], [22, 56], [23, 57],
    [24, 60], [25, 50], [26, 52], [27, 51], [28, 49], [29, 53],
    [30, 55], [31, 60], [32, 61], [33, 59], [34, 62], [35, 65],
    [36, 62], [37, 58], [38, 55], [39, 61], [40, 64], [41, 65],
    [42, 63], [43, 66], [44, 67], [45, 69], [46, 69], [47, 70],
    [48, 72], [49, 68], [50, 66], [51, 65], [52, 67], [53, 70],
    [54, 71], [55, 72], [56, 73], [57, 75], [58, 70], [59, 68],
    [60, 64], [61, 60], [62, 65], [63, 67], [64, 68], [65, 69],
    [66, 70], [67, 72], [68, 75], [69, 80]
  ]);

  var options = {
    hAxis: {
      title: 'Time'
    },
    vAxis: {
      title: 'Popularity'
    }
  };

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

  chart.draw(data, options);
}
 </script>
 <div id="chart_div"></div>

but instead having the data hardcoded in the Javascript I want to be able to send it from a servlet. Can you show some Servlet Code that does this and the corresponding JavaScript/Ajax code that reads the JSON (I presume the Servlet sends a JSON object) in the drawBasic() function and populates accordingly the data variable? Thank you in advance

Sorin
  • 105
  • 1
  • 10
  • Check [here](http://stackoverflow.com/questions/29353621/how-to-not-write-html-code-in-servlet-in-case-of-ajax/29355809#29355809) – Sas Jun 29 '16 at 16:03
  • Thank you @Sas, that seems to work, just one question - what we do if we deploy the app on a server, $.getJSON("http://localhost:8080/HEC/someservlet", function(data) {...} other than local host? You have to hardcode the name of the server there? – Sorin Jun 30 '16 at 10:35
  • You can have the ajax url as variable. So when you first calling the jsp, set a request variable in the servlet request (i.e. request.setAttribute("ajaxUrl","http://something/something"). And in your JSP insted of $.getJSON("localhost:8080/HEC/someservlet", use $.getJSON(<%=request.getAttribute("ajaxUrl") %>). – Sas Jun 30 '16 at 14:20

0 Answers0