J Yong
J Yong

Reputation: 15

Highchart in Spring boot

I try to use hightchart in spring boot to plot a line graph. But I can't get line chart but only show blank result in my view. This is my view side

    $.ajax({
        url:'${pageContext.request.contextPath}/hawker/linechartdata',
        dataType: 'json'
        success: function(result){
            var month = JSON.parse(result).month;
            var report = JSON.parse(result).report;
            drawLineChart(month, report);
        }
    
    })
    
    
    function drawLineChart(month,report){
    document.addEventListener('DOMContentLoaded', function () {
       var chart = Highcharts.chart('container', {
            chart: {
                type: 'line'
            },
            title: {
                text: 'Fruit Consumption'
            },
            xAxis: {
                categories: month
            },
            yAxis: {
                title: {
                    text: 'Fruit eaten'
                }
            },
            series: [{
                name: 'Jane',
                data: report
            }]
        });
    });     
    }
    
    <!--Here to show the graph -->
    <div id="container"></div>

My controller that use Json

    @RequestMapping("/linechartdata")
    @ResponseBody
    public String getDataFromDb(@AuthenticationPrincipal UserDetails user) {
    User currentuser = userRepository.findByUsername(user.getUsername());
    Optional<Hawker> hawker = hawkerService.getHawkerByUserId(currentuser.getId());
    //Get the report list
    List<Report> reportList = reportService.findByHawId(hawker.get().getHaw_id());

    JsonArray jsonMonth = new JsonArray();
    JsonArray jsonReport = new JsonArray();
    JsonObject json = new JsonObject();

    reportList.forEach(report->{
        jsonMonth.add(report.getMonth()+1);
        jsonReport.add(report.getTotal_sales());
    });
    json.add("month", jsonMonth);
    json.add("report", jsonReport);

    return json.toString();

When I remove the ajax and add in the manual data, it do show the graph. Please help me, Thank you.

Upvotes: 0

Views: 426

Answers (1)

ILya Cyclone
ILya Cyclone

Reputation: 954

You don't need to manually create json in your controller code, spring boot will handle it for you. You should create a dto class in a form which is expected by your javascript.

Which is in your case:

public class LineChartDto {
  private List<Integer> month; // you better call this "months" or "monthList"
  private List<BigDeciamal> report; // why do you call this "report" while this is actually "sales" 

  // all args constructor, getters
}

And your controller method would be:

@RequestMapping("/linechartdata")
@ResponseBody // or use @RestController
public LineChartDto getSalesLineChartData(..) {
  List<Report> reportList = ..

  List<Integer> months = reportList.stream()
      .map(report -> report.getMonth()+1)
      .collect(Collectors.toList());

  List<BigDecimal> sales = reportList.stream()
      .map(Report::getTotal_sales) // better name this getTotalSales
      .collect(Collectors.toList());

  return new LineChartDto(months, sales);
}

Response will result in json object:

{
  "month": [1, 2, ... ],
  "report": [100, 200, ... ]
}

As for why you ajax doesn't work - the question is too broad. Start with Chrome Dev Tools Network to check what network communication is happening, check browser console for errors, add some console.log() or better debug your js.

This line document.addEventListener('DOMContentLoaded', function () looks suspicious to me. I don't think you need to addEventListener each time you call your chart. Probably you should do this:

function drawLineChart(month,report){
    Highcharts.chart('container', {
    ...

Upvotes: 1

Related Questions