0

I am running into some troubles making variables global to where the values that are declared in the ajax function can be used in other functions. I thought by defining the variables outside of a function that when they are redefined in a function it rewrites its value and it can be used elsewhere.

Right now I am getting an error in my chart function that says totalProfileCatis not defined.

How can I make my variables global, so that they can be used in multiple functions after they are defined in the ajax function?

<div id="totalProfileViews"></div>

JS - Where I am defining the variables

//Totals
var totalProfileCat = 0; //Total Profile Catalogs

function ajaxCallCatalogs() {
    $.ajax({
        url: 'php/catalogSelect.php',
        datatype: 'json',
        success: function (data) {
            //console.log(data);
            obj = JSON.parse(data);
            totalProfileCat = obj.totalProfile; //Total Profile 
        }
    });
}
ajaxCallCatalogs();
setInterval(ajaxCallCatalogs, 150000); //1 min call 60000
console.log('value start now' + parseInt(totalCatalogs));

JS - Where I am trying to call the modified variable after the ajax function:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ['Profile Catalog', 'Blue'],
        datasets: [{
            label: '# of Votes',
            data: [totalProfileCat, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});

UPDATE 2 -- Full JS

var totalProfileCat = 0; //Total Profile Catalogs
$(document).ready(function() {

    $('.arrow').click(function() {
        var i = $(this).closest('.subViewBox').find('.subViewBoxExpand'),
            t = $(this).addClass('active');
            i.slideToggle(500).find('.subViewBoxExpand').animate({
            opacity: 1
        }, 1500) + t, $('.subViewBoxExpand').not(i).slideUp(800).prev().removeClass('active');
        //$('.subViewBoxExpand').toggleClass('active');
    });

    //Totals
    var totalCatalogs = 0; //Total Catalogs

    var totalFastCat = 0; //Total Fastening Tech Catalogs
    //Total Popular
    var totalProfilePop = 0;
    var totalFastPop = 0;
    //Total Product Specific
    var totalProfileSpec = 0;
    var totalFastSpec = 0;

    function ajaxCallCatalogs() {
        $.ajax({
            url: 'php/catalogSelect.php',
            datatype: 'json',
            success: function (data) {
                //console.log(data);
                obj = JSON.parse(data);

                totalCatalogs = obj.totalCount; //Total Catalogs
                totalProfileCat = obj.totalProfile; //Total Profile Catalogs
                totalFastCat = obj.totalFastTech; //Total Fastening Tech Catalogs
                //Total Popular
                totalProfilePop = obj.totalProfilePopular;
                totalFastPop = obj.totalFastTechPopular;
                //Total Product Specific
                totalProfileSpec = obj.totalProfileProdSpec;
                totalFastSpec = obj.totalFastTechProdSpec;

                $('#totalCatalogViews').html(totalCatalogs);
                $('#totalProfileViews').html(totalProfileCat);
                $('#totalProfilePopViews').html(totalProfilePop);
                $('#totalProfileProdViews').html(totalProfileSpec);
                $('#totalFastViews').html(totalFastCat);
                $('#totalFastTechPopViews').html(totalFastPop);
                $('#totalFastTechProdViews').html(totalFastSpec);
                //myChart.settings.data = [ { value: parseInt(totalCatalogs), color: { normal: '#00f', active: '#3b4fdb', } }, { value: parseInt(totalProfileCat), color: { normal: '#b82222', active: '#d53f00' } }, { value: parseInt(totalFastCat), color: { normal: '#51e466', active: '#59ff70' } } ];
                myChart.settings.data[0].value = parseInt(totalCatalogs); myChart.settings.data[1].value = parseInt(totalProfileCat); myChart.settings.data[2].value = parseInt(totalFastCat);
                //myChart._methods.Update(myChart);
                myChart._methods.Refresh(myChart);
            }
        });
    }
    ajaxCallCatalogs();
    setInterval(ajaxCallCatalogs, 150000); //1 min call 60000
console.log('value start now' + parseInt(totalCatalogs));
console.log('value start now for profile ' + parseInt(totalProfileCat));
    //Donut Chart
    const myChart = $("#element").jChart({

      // selectors
      elements: {
        container: null,
        body: null,
        group: null,
        figure: null,
        svg: null,
        segments: [],
        markers: null
      },

      // your own data
    data: [
        {
            value: totalCatalogs,
            color: { normal: '#00f', active: '#3b4fdb', },
            draw: true,
            push: true
        },
        {
            value: totalProfileCat,
            color: { normal: '#b82222', active: '#d53f00' },
            draw: true,
            push: true
        },
        {
            value: totalFastCat,
            color: { normal: '#51e466', active: '#59ff70' },
            draw: true,
            push: true
        }
    ],
    // values necessary for the graphing, like sum of values of all segments
        values: {},

    placeholder: {
        data: {
          value: 0, // value of the segment
          color: {
            normal: '#00a3f2', // stroke/fill color of the segment
            active: '#00d8f2',
          },
          draw: true, // whether to draw the segment on the chart or not; default true
          push: true, // whether to push the next segment via offset. Best to set false together when draw is set to false (the empty section will always be at the end that way); default true
          order: null, // drawing order
          title: '',
          strokeWidth: 3
        }
    },

      // appearance options
      appearance: {
        type: 'donut', // or 'pie', 'bar'
        subType: 'path',
        baseColor: '#ddd',
        segmentColor: {
            normal: '#00a3f2',
            active: '#00d8f2',
        },
        baseOffset: 0, // offset for starting point of first segment
        baseStrokeWidth: 1,
        strokeWidth: 3, // default stroke width for all segments
        animated: true,

        title: {
          chartTitle: '',
          showValue: true, // tooltips
          showPercentage: true,
          showSummary: true, // summary - show a value inside the donut chart
          summaryTitle: parseInt(totalCatalogs), // by default it shows the percentage of the greatest segment in the chart
          // (if summaryTitle is empty)
          summarySegment: null // the segment's id which percentage will be displayed in the summary
        },

        /* DONUT AND CIRCLE */

        radius: 100 / (2 * Math.PI),
        innerCutout: 0.75, // how "thin" the segments are from the center point. (0 will render a pie chart (full circle))
        centerX: 21,
        centerY: 21,

        /* DONUT */
        //subType: 'circle', // render type: circle for circle based approach, path for line and arc approach using path
        isGauge: false, // if the donut will be rendered as a full circle or a half-circle
        gap: 0, // gap between segments for donut chart (in percentage, 1 = 1%)
      },

      // callback function
      callbacks: {
        onInit() {
        },
        onRefresh() {
        },
        onSegmentMouseover() {
        },
        onSegmentMouseout() {
        }
      }

    });
});

//chart.js
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ['Profile Catalog', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [totalProfileCat, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
Paul
  • 3,348
  • 5
  • 32
  • 76

1 Answers1

0

Your totalProfileCat variable is declared inside $ ( document ).ready(). Meaning, it will be initialized only after the DOM is loaded and it's scope is ready() function.

However, you use it outside the ready() function when initializing your new Chart object. Hence the error.

Initialize the variable outside the ready() function and it should be okay.

Prerak Sola
  • 9,517
  • 7
  • 36
  • 67
  • This stopped the undeclared error, but when I am trying to call it again further down the page the value is 0 rather than the updated value. – Paul Jul 12 '19 at 16:16
  • You mean inside the `ajaxCallCatalogs()` ? Did you remove the initialization from the `ready()` ? – Prerak Sola Jul 12 '19 at 16:20
  • Yes, the variables that are modified in the ajaxCallCatalogs function. What do you mean by removing the initialization from the `ready()`? – Paul Jul 12 '19 at 16:24
  • Could you post the updated code? And try logging the variable in console after it is updated via ajax to narrow down the issue. – Prerak Sola Jul 12 '19 at 16:26
  • I have the console.log for the value. It is showing 0. Code updated in question. – Paul Jul 12 '19 at 16:28
  • `console.log('value start now for profile ' + parseInt(totalProfileCat));` will not wait for the ajax call to finish as ajax is asynchronous. Try logging the value after the line `totalProfileCat = obj.totalProfile;` and you should see the value returned in the response. – Prerak Sola Jul 12 '19 at 16:33
  • I am getting the correct values in my ajax function. That isn't the issue. It is getting the correct value where I am declaring it in the chart function. – Paul Jul 12 '19 at 16:39