Chartjs-Chart.js not displaying Django Rest API data

0👍

At the code for chart.js, try to change url endpoint to http address

$(document).ready(function(){
$.datepicker.setDefaults({
    dateFormat: 'yy-mm-dd'
  });
  $("#firstdatepicker").datepicker();
  $("#lastdatepicker").datepicker();
  $("#filter").click(function() {
    var from_date = $("#firstdatepicker").val();
    var to_date = $("#lastdatepicker").val();
    if (from_date != '' && to_date != '') {
      console.log(from_date, to_date);
      var endpoint = '/api/data'
  $.ajax({
    method: "GET",
    dataType: "json",
    url: "http://your-server:port/api/data/",
    data: {
      from_date: from_date,
      to_date: to_date
    },
    success: function(data){
      //check the data, if it's already return the correct array mentioned at the beginning of the question
      console.log(data);

      var ctx = document.getElementById("myChart2").getContext('2d');
      var myChart = new Chart(ctx, {
          type: 'line',
          data: {
              labels: data.timestamp,
              datasets: [{
                  label: 'moisture',
                  data: data.moisture,
                  backgroundColor: [
                      'rgb(68, 145, 252)'
                  ],
                  borderColor: [
                  '#331698'
                  ],
                  borderCapStyle: 'round',
                  borderWidth: 1
              }]
          },
          options: {
              reponsive: true,
              scales: {
                  yAxes: [{
                      ticks: {
                          beginAtZero:true,
                          max:100,
                          stepSize:10
                      },
                        scaleLabel: {
                        display:     true,
                        labelString: 'moisture'
                    }
                  }],
                  xAxes: [{
                          display: true,
                          ticks: {
                            min: from_date,
                            max: to_date,
                          },
                          type: 'time',
                          time: {
                            displayFormats: {
                              second: 'h:mm:ss a'
                            }
                          },
                        scaleLabel: {
                        display:     true,
                        labelString: 'Date'
                    }
                  }]
              }
          }
      });
    },
    error: function(error_data){
      console.log(error_data)
    }
  });
} else {
  alert("Please Select Date");
}
  });    })

Leave a comment