0

i am not very well on javascript , below are the code which i want get variable from JSON and put the date on the chart as label .Below are the code

function getdate(num){
$.ajax({                              
    url: 'http://81.12.18.111/fibarobiz/showjson.php',
    data: "device=41", 
    dataType: 'json', 
     
          success: function(data)         
          {
         var aMon= data.date[num]; 
   // var aMon = '2/18';
   return aMon;    <--no value to return
           //    var pmvalue =data.properties.value;
   //   $('#pm25v').append( pmvalue );
   
       } 
     
        });
}
$(function() {
    "use strict";
 var Mon=getdate(0); <-- outcome always undefined
    // ============================================================== 
    // Revenue
    // ============================================================== 
 var ctx = document.getElementById('revenue').getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'line',

                data: {
                    //labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
     labels: [Mon, 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                    datasets: [{
                        label: 'Current Week',
                        data: [12, 19, 3, 17, 6, 3, 7],
                      backgroundColor: "rgba(89, 105, 255,0.5)",
                                    borderColor: "rgba(89, 105, 255,0.7)",
                                    borderWidth: 2
                        
                    }
                    ......

No matter i use static value for variable "aMon" , it can't to return any value . i think that it can't to run ajax in JS file? Please help!! Many Thanks!

Wilson

  • because ajax is async, it did not wait return value and go to next line of code, you can set async: false or move your code below inside success function – Hien Nguyen Feb 23 '19 at 08:52
  • Hi Hien , sorry that i can't get your point ,you mean i put ajax part inside the $(function () ? Because i also tested but also don't work...could you give me some suggest code? Many Thanks – Wilson Chan Feb 23 '19 at 09:12
  • no, move these var ctx = document.getElementById('revenue').getContext('2d'); to success function of AJAX – Hien Nguyen Feb 23 '19 at 09:13
  • That Work! Thank your help! – Wilson Chan Feb 23 '19 at 14:50

0 Answers0