Search code examples
javascriptjqueryajaxjquery-deferred

Prevent any Ajax XHR GETs returning 500 Error on page load


I have 4 charts in my page.

enter image description here

I simply make a AJAXGETs to 4 APIs, got data back, and graph it.

Issue : One of my Ajax is returning 500 error.


I've tried to do all my action in the .done() like this

var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/zero-rate'});
ajax.done(function (data) {
    //do stuffs ... 
});

But that doesn't seem to help.


When I refresh my page, under Network Tab I always see one of these ajax XHR GET is red(500) as this image below.

enter image description here


Note :

  • It's not reproducable all the time.
  • Sometimes, 2 returns errors.
  • Sometimes, different GETs return error.
  • Sometimes, all of those GETs working fine without error.

How do I prevent these errors and make sure all those GETs work before start rendering ?

Should I start looking into JS promise or jQuery Defered Object ?

I don't know much about those yet.


Entire Code

@extends('layouts.internal.master')
@section('content')

<div class="row">
  <div class="col-md-10 col-md-offset-1">
    <div id="gragh_ubb_0_rate"></div>
  </div>
</div>

<div class="row">
  <div class="col-md-10 col-md-offset-1">
    <div id="gragh_ubb_hour"></div>
  </div>
</div>



<div class="row">
  <div class="col-md-10 col-md-offset-1">
    <div id="gragh_ubb_day"></div>
  </div>
</div>

<div class="row">
  <div class="col-md-10 col-md-offset-1">
    <div id="graph_month"></div>
  </div>
</div>



@stop


{{-- Page-specific scripts --}}
@section('pagescripts')


<script type="text/javascript" src="/js/fusioncharts/fusioncharts.js"></script>
<script type="text/javascript" src="/js/fusioncharts/fusioncharts.charts.js"></script>

<script type="text/javascript">


  //constants

  var graph_ubb_configs = {

    "subcaption": "",
    "yaxisname": "Bandwidth (KB)",
    "formatnumberscale": "1",
    "plotgradientcolor": "#0075c2",
    "palettecolors": "#03A9F4",
    "bgcolor": "FFFFFF",
    "showalternatehgridcolor": "0",
    "showplotborder": "0",
    "showvalues": "0",
    "labeldisplay": "WRAP",
    "divlinecolor": "CCCCCC",
    "suseroundedges": "1",
    "showcanvasborder": "0",
    "canvasborderalpha": "0",
    "defaultnumberscale": "KB",
    "showborder": "0",
    "captionFontSize": "14",
    "subcaptionFontSize": "14",
    "baseFont": "Roboto",
    "subcaptionFontBold": "0",
    "subcaptionFontSize": "12",
    "subcaptionFontBold": "0",
    "subcaptionFontColor": "#08c",
  };

  var t_line = [{"line": [{"startvalue": '{{ $total_bytes }}', "color": "#F44336", "valueOnRight": "1", "tooltext": "Limit", "displayvalue": "Threshold", "dashed": "1"} ] } ];

  var c_time = '{{ $hour }}';


  /*================================
  =            Zero Rate           =
  ================================*/
  // 1-31 days


  var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/zero-rate'});
  ajax.done(function (data) {

    console.log('%c Zero Rate API ', 'background: #222; color: #bada55');
    console.log(data);

    if(data != null){

      var up_link = data.zero_rate_vlan['up_bytes']/1000000;
      var down_link = data.zero_rate_vlan['down_bytes']/1000000;


      console.log(up_link);
      console.log(down_link);




      graph_ubb_configs.caption = "Zero Rated Traffic";
      graph_ubb_configs.subcaption = data.m + '/' + data.d + '/' + data.y;
      graph_ubb_configs.xaxisname = "Bandwidth";


      var gragh_ubb_0_rate = new FusionCharts({
        "type": "bar2d",
        "renderAt": "gragh_ubb_0_rate",
        "width": "100%",
        "dataFormat": "json",
        "dataSource": {
          "chart": graph_ubb_configs,
          "data":[{"label": "Uplink","value":parseFloat(up_link)}, {"label": "Downlink","value":parseFloat(down_link)}],
          "trendlines": t_line

        }
      });

      gragh_ubb_0_rate.render();

      console.log('%c ------------------------------------------------------------------------ ', 'color: #0075c2');

    }





  });








  var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/hour'});

  ajax.done(function (data) {

    // delete data.hour_p_ubb[0];

    console.log('%c HOUR API ', 'background: #222; color: #bada55');
    console.log(data);


    var hour = [];

    for(var i=0; i<24; i++) {

      var time = i%12;

      if(time == 0){
        time = 12;
      }

      if(i<12){
        var am = 'AM';
      }else{
        var am = 'PM';
      }

      var val = data.hour_p_ubb[i]['up_bytes']/1000000 + data.hour_p_ubb[i]['down_bytes']/1000000;
      var object = {"label":time + ' ' + am,"value": + val};
      hour[i] = object;

    }

    console.log('%c HOUR Value ', 'background: #222; color: #bada55');
    console.log(JSON.stringify(hour));

    graph_ubb_configs.caption = "Daily Network Usage";
    graph_ubb_configs.subcaption = data.m + '/' + data.d + '/' + data.y + ' ( '+data.time+' )';
    graph_ubb_configs.xaxisname = "Hours of Day";

    var gragh_ubb_hour = new FusionCharts({
      "type": "column2d",
      "renderAt": "gragh_ubb_hour",
      "width": "100%",
      "dataFormat": "json",
      "dataSource": {
        "chart": graph_ubb_configs,
        "data":hour,
        // "trendlines": t_line

      }
    });


    gragh_ubb_hour.render();

    console.log('%c ------------------------------------------------------------------------ ', 'color: #0075c2');

  });



  /*=============================
  =            DAY            =
  =============================*/
  // 1-31 days


  var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/day'});
  ajax.done(function (data) {

    console.log('%c DAY API ', 'background: #222; color: #bada55');
    console.log(data);

    // var day = [];
    var labels = [];
    var values = [];

    for(var i=0; i<data.day_p_ubb.length; i++) {

      var up_link = parseFloat(data.day_p_ubb[i]['up_bytes'])/1000000;
      var down_link = parseFloat(data.day_p_ubb[i]['down_bytes'])/1000000;
      var val = parseFloat(up_link+down_link);
      var c_d = data.d;

      if(i == 0){
        var c_val = 0;
      }else{

        if(i <= c_d ){
          var c_val = parseFloat(c_val) + parseFloat(val);
        }else{
          var c_val = '';
        }

      }

      var label_object = {"label":String(i+1)};
      var data_object = {"value":parseFloat(c_val)};

      labels[i] = label_object;
      values[i] = data_object;

    }

    graph_ubb_configs.caption = "Monthly Network Usage";
    graph_ubb_configs.subcaption = data.m + '/' + data.d + '/' + data.y;
    graph_ubb_configs.xaxisname = "Days of Month";


    var gragh_ubb_day = new FusionCharts({
      "type": "msline",
      "renderAt": "gragh_ubb_day",
      "width": "100%",
      "dataFormat": "json",
      "dataSource": {
        "chart": graph_ubb_configs,
        "categories": [{"category": labels } ], "dataset": [{"data": values } ],
        "trendlines": t_line

      }
    });

    gragh_ubb_day.render();

    console.log('%c ------------------------------------------------------------------------ ', 'color: #0075c2');


  });







  /*============================
  =            Month           =
  ============================*/

  var ajax = $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/month'});
  ajax.done(function (data) {

    console.log('%c MONTH API ', 'background: #222; color: #bada55');
    console.log(data);

    var month = [];
    for(var i=0; i<12; i++) {

      var val = data.month_p_ubb[i]['up_bytes']/1000000 + data.month_p_ubb[i]['down_bytes']/1000000;

      if(i == 0){
        var object = {"label":'January',"value": val};
      }else if(i == 1){
        var object = {"label":'Febuary',"value": val};
      }else if(i == 2){
        var object = {"label":'March',"value": val};
      }else if(i == 3){
        var object = {"label":'April',"value": val};
      }else if(i == 4){
        var object = {"label":'May',"value": val};
      }else if(i == 5){
        var object = {"label":'June',"value": val};
      }else if(i == 6){
        var object = {"label":'July',"value": val};
      }else if(i == 7){
        var object = {"label":'August',"value": val};
      }else if(i == 8){
        var object = {"label":'September',"value": val};
      }else if(i == 9){
        var object = {"label":'October',"value": val};
      }else if(i == 10){
        var object = {"label":'November',"value": val};
      }else{
        var object = {"label":'December',"value": val};
      }

      month[i] = object;
    }

    console.log('%c Month Value', 'background: #222; color: #bada55');
    console.log(JSON.stringify(month));


    graph_ubb_configs.caption = "Yearly Network Usage";
    graph_ubb_configs.subcaption = data.m + '/' + data.d + '/' + data.y;
    graph_ubb_configs.xaxisname = "Months of Year";


    var graph_month = new FusionCharts({
      "type": "column2d",
      "renderAt": "graph_month",
      "width": "100%",
      "dataFormat": "json",
      "dataSource": {
        "chart": graph_ubb_configs,
        "data":month,
        "trendlines": t_line
      }
    });

    graph_month.render();

    console.log('%c ------------------------------------------------------------------------ ', 'color: #0075c2');

  });

</script>


@stop

Solution

  • Sounds like you might need to make the ajax call sequentially instead of in-parallel.

    First, wrap your four parts in function() {...} and return jqXHR from each.

    function make_zero_rate_graph() {
        /*================================
        =            Zero Rate           =
        ==================================*/
        // 1-31 days
        return $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/zero-rate'}).then(function(data) {
            if(data) {
                var gragh_ubb_0_rate = new FusionCharts({
                    'type': 'bar2d',
                    'renderAt': 'gragh_ubb_0_rate',
                    'width': '100%',
                    'dataFormat': 'json',
                    'dataSource': {
                        'chart': $.extend({}, graph_ubb_configs, {
                            'caption': 'Zero Rated Traffic',
                            'subcaption': [data.m, data.d, data.y].join('/'),
                            'xaxisname': 'Bandwidth'
                        }),
                        'data': [
                            { 'label': 'Uplink', 'value': +data.zero_rate_vlan.up_bytes / 1000000 }, 
                            { 'label': 'Downlink', 'value': +data.zero_rate_vlan.down_bytes / 1000000 }
                        ],
                        'trendlines': t_line
                    }
                });
                gragh_ubb_0_rate.render();
            }
        });
    }
    
    function make_hour_graph() {
        /*===========================
        =            Hour           =
        =============================*/
        return $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/hour'}).then(function(data) {
            var gragh_ubb_hour = new FusionCharts({
                'type': 'column2d',
                'renderAt': 'gragh_ubb_hour',
                'width': '100%',
                'dataFormat': 'json',
                'dataSource': {
                    'chart': $.extend({}, graph_ubb_configs, {
                        'caption': 'Daily Network Usage',
                        'subcaption': data.m + '/' + data.d + '/' + data.y + ' ( '+data.time+' )',
                        'xaxisname': 'Hours of Day'
                    }),
                    'data': data.hour_p_ubb.slice(0, 24).map(function(item, i) {
                        return {
                            'label': (i%12 || 12) + ' ' + ((i<12)?'AM':'PM'),
                            'value': (+item.up_bytes + +item.down_bytes) / 1000000
                        });
                    }),
                    // 'trendlines': t_line
                }
            });
            gragh_ubb_hour.render();
        });
    }
    
    function make_day_graph() {
        /*===========================
        =            DAY            =
        =============================*/
        // 1-31 days
        return $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/day'}).then(function (data) {
            var c_val = 0;
            var gragh_ubb_day = new FusionCharts({
                'type': 'msline',
                'renderAt': 'gragh_ubb_day',
                'width': '100%',
                'dataFormat': 'json',
                'dataSource': {
                    'chart': $.extend({}, graph_ubb_configs, {
                        'caption': 'Monthly Network Usage',
                        'subcaption': data.m + '/' + data.d + '/' + data.y,
                        'xaxisname': 'Days of Month'
                    }),
                    'categories': [{
                        'category': data.day_p_ubb.map(function(_, i) {
                            return { 'label': String(i+1) };
                        })
                    }],
                    'dataset': [{
                        'data': data.day_p_ubb.map(function(item, i) {
                            c_val += (i > 0 && i <= data.d) ? ((+item.up_bytes + +item.down_bytes) / 1000000) : 0;
                            return { 'value': c_val };
                        })
                    }],
                    'trendlines': t_line
                }
            });
            gragh_ubb_day.render();
        });
    }
    
    function make_month_graph() {
        /*============================
        =            Month           =
        ==============================*/
        var months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November','December'];
        return $.ajax({url: '/api/timebase/'+'{{ $cpe_mac }}/month'}).then(function (data) {
            var graph_month = new FusionCharts({
                'type': 'column2d',
                'renderAt': 'graph_month',
                'width': '100%',
                'dataFormat': 'json',
                'dataSource': {
                    'chart': $.extend({}, graph_ubb_configs, {
                        'caption': 'Yearly Network Usage',
                        'subcaption': [data.m, data.d, data.y].join('/'),
                        'xaxisname': 'Months of Year'
                    }),
                    'data': data.month_p_ubb.slice(0,12).map(function(data, i) {
                        return {
                            'label': months[i],
                            'value': (+data.up_bytes + +data.down_bytes) / 1000000
                        };
                    }),
                    'trendlines': t_line
                }
            });
            graph_month.render();
        });
    }
    

    Code within the functions is tidied but not tested

    With those functions in place, calling in sequence is trivial :

    // List the functions in an array 
    var fns = [ make_zero_rate_graph, make_hour_graph, make_day_graph, make_month_graph ];
    
    // And build a then() chain by reducing the array,
    // see http://stackoverflow.com/documentation/javascript/231/promises/5917/#t=201612121359154320486
    fns.reduce(function(jqPromise, fn) {
        return jqPromise.then(fn);
    }, $.when());