Javascript doesn't execute ajax call code sometimes

2020-05-26 javascript html ajax asp.net-mvc raphael

I am creating a gauge chart using Raphael.js. I am using ajax to call a service that will return data that is to be shown in gauge chart. My application has multiple HTML pages where this gauge chart should be shown, so I have created a common Layout HTML file for make chart code common. I am using MVC CSHTML pages.

So the problem is, from the first HTML page when when I call the javascript code to generate gauge chart ajax code executes fine and returns data. But from another page all ajax part of the code just gets skipped and I have no data to bind in the gauge. And there is no error message in console also.

Here is the JS code for gauge generation:

(function ($, window, document, undefined) {
    debugger;
    var leadid = jQuery("#hdnSessionLeadId").data('value');
    var scoreNeeded = jQuery("#hdnscoreNeeded").data('value');
    var min = 0;
    var max = 0;
    var value = 0;
    var insurabilityScore = 0;
    var scoreAvg = 0;
    var description = '';
    $.ajax({
        url: "GaugeChartData?Lead_ID=" + leadid + "&Lob=Auto&scoreNeeded=" + scoreNeeded,
        dataType: "json",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        async: false,
        cache: false,
        success: function (data) {
            if (data != "") {
                data = JSON.parse(data);
                min = data.scoreMin;
                max = data.scoreMax;
                debugger;
                insurabilityScore = data.insurabilityScore;
                insurabilityScore = 700;
                description = 'Excellent';

                if (insurabilityScore == 0) {
                    description = '';
                    insurabilityScore = '';
                }
                else {
                    //description = data.description;
                }
                 scoreAvg = data.scoreAvg;
                 value = data.insurabilityScore;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('Got an Error');
        }
    });
    var config = {
        radius: 80,
        paddingX: 0,
        paddingY: 0,
        gaugeWidth: 15,

        fill: '0-#FE5249:5-#FA8B1B:12-#F8A903:20-#70CD60:90-#19C1E6:100-#19C1E6',
        gaugeBackground: '#f4f4f4',
        background: '#fff',

        showNeedle: true,
        showNeedles: true,
        animationSpeed: 1200,

        width: 200,
        height: 120,
        centerX: 0,
        centerY: 0,

        min: min,
        max: max,
        value: 0, 
        scoreAvg: scoreAvg,
        insurabilityScore: insurabilityScore,
        description: description,

        valueLabel: {
            display: true,
            fontFamily: 'Arial',
            fontColor: '#1ABFE9',
            fontSize: '50',
            fontWeight: 'normal',
            value: insurabilityScore,
        },
        valueLabel2: {
            display: true,
            fontFamily: 'Arial',
            fontColor: '#1ABFE9',
            fontSize: '18',
            fontWeight: 'normal',
            value: description,
        },
        title: {
            display: true,
            value: 'Avg',
            fontFamily: 'Arial',
            fontColor: '#000',
            fontSize: '10',
            fontWeight: 'normal',
            centerX: 0,
            centerY: 0,
        },
        title2: {
            display: true,
            value: 'You',
            fontFamily: 'Arial',
            fontColor: '#000',
            fontSize: '10',
            fontWeight: 'normal',
            centerX: 0,
            centerY: 0,
        },
        label: {
            display: true,
            left: min,
            right: max,
            fontFamily: 'Arial',
            fontColor: '#000',
            fontSize: '12',
            fontWeight: 'normal'
        }
    };

    // Create an arc with raphael.js
    Raphael.fn.arc = function (startX, startY, endX, endY, radius1, radius2, angle) {
        var arcSVG = [radius1, radius2, angle, 0, 1, endX, endY].join(' ');
        return this.path('M' + startX + ' ' + startY + ' a ' + arcSVG);
    };

    // Calculate a circular arc with raphael.js
    Raphael.fn.circularArc = function (centerX, centerY, radius, startAngle, endAngle) {
        var startX = centerX + radius * Math.cos(startAngle * Math.PI / 180);
        var startY = centerY + radius * Math.sin(startAngle * Math.PI / 180);
        var endX = centerX + radius * Math.cos(endAngle * Math.PI / 180);
        var endY = centerY + radius * Math.sin(endAngle * Math.PI / 180);
        return this.arc(startX, startY, endX - startX, endY - startY, radius, radius, 0);
    };


    // The kuma Gauge constructor
    function kumaGauge(element, options, method) {
        // This
        var _this = this;
        // The element
        _this.element = element;
        _this.$element = $(element);
        // The config
        _this.config = $.extend({}, config, options);
        _this._config = config;
        _this.method = method;
        // The actual gauge
        _this.gauge = {};
        // Initialise
        _this.init();
    }

    // Extend the kumaGauge object
    kumaGauge.prototype = {
        init: function () {
            // this
            _this = this;
            if (!_this.method) {
                _this.draw();
            }
        },
        _setup: function () {
            // This
            _this = this;
            // Calculate some values needed do draw the gauge
            _this.config.width = (_this.config.radius * 2) + (_this.config.paddingX * 2);
            _this.config.height = _this.config.radius + (_this.config.paddingY * 2);
            _this.config.centerX = _this.config.paddingX + _this.config.radius;
            _this.config.centerY = _this.config.paddingY + _this.config.radius;
            // The div wich acts as the canvas needs an id, so we give it a unique one if it doesn't have one
            if (typeof $(this).attr('id') === 'undefined' || $(this).attr('id') === '') {
                _this.config.id = 'gauge-' + $('*[id^="gauge-"]').length;
                _this.$element.attr('id', _this.config.id);
            }
        },
        _calculateRotation: function (min, max, val) {
            var _range, _rotation;
            _range = max - min;

            if (val < max && val > min) {
                _rotation = 180 * ((val - min) / _range);
            } else if (val <= min) {
                _rotation = 0;
            } else {
                _rotation = 180;
            }

            return _rotation;
        },
        draw: function () {
            //this
            var _this = this;

            // Setup all the needed config variables
            _this._setup();

            // Make the base drawing Canvas
            _this.gauge = new Raphael(_this.config.id, _this.config.width, _this.config.height);

            // Draw the gauge
            _this.gauge.gauge = _this.gauge.circularArc(_this.config.centerX, _this.config.centerY,
                _this.config.radius, 180, 0);
            _this.gauge.gauge.attr({
                'fill': _this.config.fill,
                'stroke': 'none',
                'height':'120px'
            });
            _this.gauge.gauge.node.setAttribute('class', 'gauge');

            // Draw the gauge background
            _this.gauge.gaugeBackground = _this.gauge.circularArc(_this.config.centerX, _this.config.centerY,
                _this.config.radius, 180, 0);
            _this.gauge.gaugeBackground.attr({
                'fill': _this.config.gaugeBackground,
                'stroke': 'none'
            });
            _this.gauge.gaugeBackground.node.setAttribute('class', 'gauge__background');

            // Draw the white center arc
            _this.gauge.centerArc = _this.gauge.circularArc(_this.config.centerX, _this.config.centerY,
                _this.config.radius - _this.config.gaugeWidth, 180, 0);
            _this.gauge.centerArc.attr({
                'fill': _this.config.background,
                'stroke': 'none'
            });
            _this.gauge.centerArc.node.setAttribute('class', 'gauge__center');
            _this.gauge.title2 = _this.gauge.text(_this.config.centerX - -50, _this.config.paddingY - -5,
                _this.config.title2.value);
            _this.gauge.title2.attr({
                'fill': '#55E5DA',
                'fill-opacity': 0,
                'font-size': _this.config.title2.fontSize,
                'font-family': _this.config.title2.fontFamily,
                'font-weight': _this.config.title2.fontWeight
            });

            //Draw the needle

            // Draw the bottom mask to hide the rotated background arc
            _this.gauge.bottomMask = _this.gauge.rect(0, _this.config.centerY, _this.config.width, 40);
            _this.gauge.bottomMask.attr({
                'fill': _this.config.background,
                'stroke': 'none'
            });

            // Draw the text container for the value
            if (_this.config.valueLabel.display) {

                    _this.gauge.valueLabel = _this.gauge.text(_this.config.centerX, _this.config.centerY - 30,
                        _this.config.insurabilityScore);

                _this.gauge.valueLabel.attr({
                    'fill': _this.config.valueLabel.fontColor,
                    'font-size': _this.config.valueLabel.fontSize,
                    'font-family': _this.config.valueLabel.fontColor,
                    'font-weight': _this.config.valueLabel.fontWeight
                });
                _this.gauge.valueLabel.node.setAttribute('class', 'gauge__value');
                _this.gauge.valueLabel.node.setAttribute('display', 'block');
            }
            // Draw the text container for the value
            if (_this.config.valueLabel2.display) {
                debugger;

                    _this.gauge.valueLabel2 = _this.gauge.text(_this.config.centerX, _this.config.centerY -0,
                        _this.config.description);

                _this.gauge.valueLabel2.attr({
                    'fill': _this.config.valueLabel2.fontColor,
                    'font-size': _this.config.valueLabel2.fontSize,
                    'font-family': _this.config.valueLabel2.fontColor,
                    'font-weight': _this.config.valueLabel2.fontWeight
                });
                _this.gauge.valueLabel2.node.setAttribute('class', 'gauge__value2');
                _this.gauge.valueLabel.node.setAttribute('display', 'block');
            }



            if (_this.config.label.display) {
                // Draw the left label
                _this.gauge.leftLabel = _this.gauge.text((_this.config.gaugeWidth / 2) + _this.config.paddingX + 2,
                    _this.config.centerY + 5, _this.config.label.left);
                _this.gauge.leftLabel.attr({
                    'fill': _this.config.title.fontColor,
                    'fill-opacity': 0,
                    'font-size': _this.config.label.fontSize,
                    'font-family': _this.config.label.fontFamily,
                    'font-weight': _this.config.label.fontWeight
                });
                _this.gauge.leftLabel.node.setAttribute('class', 'gauge__label--left');

                // Draw the right label
                _this.gauge.rightLabel = _this.gauge.text((_this.config.width - (_this.config.gaugeWidth / 2)) - _this.config.paddingX,
                    _this.config.centerY + 10, _this.config.label.right);
                _this.gauge.rightLabel.attr({
                    'fill': _this.config.title.fontColor,
                    'fill-opacity': 0,
                    'font-size': _this.config.label.fontSize,
                    'font-family': _this.config.label.fontFamily,
                    'font-weight': _this.config.label.fontWeight
                });
                _this.gauge.rightLabel.node.setAttribute('class', 'gauge__label--right');
            }

            setTimeout(function () {

                if (_this.config.title.display) {
                    _this.gauge.title.attr({
                        'fill-opacity': 1
                    });
                }
                if (_this.config.title2.display) {
                    _this.gauge.title2.attr({
                        'fill-opacity': 1
                    });
                }
                if (_this.config.label.display) {
                    _this.gauge.leftLabel.attr({
                        'y': _this.config.centerY + (_this.gauge.leftLabel.getBBox().height / 2),
                        'fill-opacity': 1,
                    });
                    _this.gauge.rightLabel.attr({
                        'y': _this.config.centerY + (_this.gauge.rightLabel.getBBox().height / 2),
                        'fill-opacity': 1,
                    });
                }
            }, 1000);
            // Animate the gauge to the right value position
            _this.gauge.gaugeBackground.animate({
                transform: 'r' +
                    _this._calculateRotation(_this.config.min, _this.config.max, _this.config.value) + ',' +
                    _this.config.centerX + ',' + _this.config.centerY
            }, _this.config.animationSpeed, '<>');

        },
        update: function (data) {
            //this
            var _this = this;
            var updateGauge = function (min, max, value) {
                _this.config.min = min;
                _this.config.max = max;
                _this.config.value = value;

                // Update the rotation of the gauge
                _this.gauge.gaugeBackground.animate({
                    transform: 'r' +
                        _this._calculateRotation(min, max, value) + ',' +
                        _this.config.centerX + ',' + _this.config.centerY
                }, _this.config.animationSpeed, '<>');

                // Update the value label
                if (_this.config.valueLabel.display) {
                    if (_this.config.showNeedle) {
                        _this.gauge.valueLabel.attr('text', value);
                    } else {
                        _this.gauge.valueLabel.attr('text', 500);
                    }
                }
            };

            if (typeof data.min !== 'undefined' && typeof data.max !== 'undefined' && typeof data.value !== 'undefined') {
                updateGauge(data.min, data.max, data.value);
            } else if (typeof data.value !== 'undefined') {
                updateGauge(_this.config.min, _this.config.max, data.value);
            }
        }
    };
    $.fn.kumaGauge = function (method, options) {
        var _method = method,
            _arguments = arguments,
            _this = this;
        if (typeof _method !== 'string') {
            if (_arguments.length === 1) {
                options = _method;
                method = false;

                return this.each(function () {
                    if (!$.data(this, 'kumaGauge')) {
                        $.data(this, 'kumaGauge', new kumaGauge(this, options, method));
                    }
                });
            }
        } else {
            return this.each(function () {
                if (typeof $.data(this, 'kumaGauge')[method] === 'function') {
                    $.data(this, 'kumaGauge')[method](options);
                }
            });
        }
    };
})(jQuery, window, document);

Chart generated on first page is shown in first picture. Chart generated on second page is in the second Picture. As ajax call is not executed I have no data to show on this gauge chart so there is missing data

The div section where gauge is generated:

<div class="js-gauge js-gauge--1 gauge scaling-svg"></div>

This is how function is called from document.ready:

<script type="text/javascript">

    $('.js-gauge--1').kumaGauge({
        value: 1000,
    });
</script>

Answers

Related