Vorbly Code | WIX IFRAME GRAPHS & CHARTS WITH FILTERS

Vorbly <Code>

CODING MADE EASY WITH VORBLY

WIX IFRAME GRAPHS & CHARTS WITH FILTERS

Need to add professional charts to your Wix website? This tutorial will show you how to add graphs and charts to your website using Wix HTML iframe. Populate chart with data from your databases and include filters to engage your visitors. We will provide you with the webpage elements and sample codes required to implement this feature.

THE DEMO

1/3

THE ELEMENTS

The Page

HTML iFrame: #html1

Dropdown Input: #dropdown1

Wix Table: #table1

The Database

Create a database Expenses.

Recommended fields:

  • Month ID: month

  • Expense Type ID: type

  • Expense Amount ID: amount

THE CODE

Page Code

import wixData from 'wix-data';

import {monthSort} from 'public/months';

 

$w.onReady(function () {

    $w("#table1").columns = [

    {

          "id": "col1",

          "dataPath": "month",

          "label": "Month",

          "type": "string"

    },

    {

          "id": "col2",

          "dataPath": "total",

          "label": "Total Expenses",

          "visible": true,

          "type": "number"

    }

  ];

wixData.query("Expenses")

    .ascending("month")

    .limit(1000)  // Max limit of 1,000 //

    .find()

    .then( (result) => {

      const months = result.items.map(x => x.month)

          .filter((obj, index, self) => index === self.indexOf(obj))

          .sort(monthSort);

      const aggregated = months.map(x => {

          return {

             month: x,

             total: result.items.filter(obj => obj.month === x)

                       .map(z => z.amount)

                       .reduce((sum, current) => sum + current)

          };

      });

      $w("#table1").rows = aggregated;

let tableArr = [];

for ( var i = 0; i < $w("#table1").rows.length; i++ ) {

        tableArr.push (

             $w("#table1").rows[i]["total"]

        )

}

        $w("#html1").postMessage(tableArr);

        });

});


 

export function dropdown1_change(event, $w) {

 

let product = $w("#dropdown1").value;

 

   $w("#table1").columns = [

       {

         "id": "col1",

         "dataPath": "month",

         "label": "Month",

         "type": "string"

       },

       {

         "id": "col2",

         "dataPath": "total",

         "label": "Total Expenses",

         "visible": true,

         "type": "number"

       }

   ];

 

   wixData.query("Expenses")

       .ascending("month")

       .eq("type", product)

       .limit(1000)

       .find()

       .then( (result) => {

         const months = result.items.map(x => x.month)

             .filter((obj, index, self) => index === self.indexOf(obj))

             .sort(monthSort);

         const aggregated = months.map(x => {

             return {

                month: x,

                total: result.items.filter(obj => obj.month === x)

                          .map(z => z.amount)

                          .reduce((sum, current) => sum + current)

             };

      });

 

$w("#table1").rows = aggregated;

let tableArr = [];

for ( var i = 0; i < $w("#table1").rows.length; i++ ) {

       tableArr.push (

            $w("#table1").rows[i]["total"]

       )

}

 

console.log(tableArr);

    $w("#html1").postMessage(tableArr);

});

 

}

// Chart Type Reference

// 1. Line Graph : 'line'

// 2. Bar Graph : 'bar'

// 3. Radar Chart : 'radar'

// 4. Pie Chart : 'pie'

// 5. Doughbut Chart : 'doughnut'

// 6. Polar Chart : 'polarArea'

// 7. Bubble Chart : 'bubble'

// 8. Scatter Plot : 'scatter'

// For full API documentation: Visit Chartjs.org //

Public Code

// months.js //

 

const months = [ "January", "February", "March", "April",

"May", "June", "July", "August", "September", "October", "November", "December" ];

 

export function monthSort(a, b) {

    return months.indexOf(a) - months.indexOf(b);

}

HTML iframe

// Copy and paste in HTML iframe //

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.min.js"></script>
</head>
<body onLoad="ready()">
<canvas id="myChart" width="250" height="80"></canvas>
<script>

  var ctx = document.getElementById("myChart");

  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
      datasets: [{
        label: 'Household Expenses',
        data: [],//start empty
        backgroundColor: [
'rgba(10, 168, 196, 0.2)',
'rgba(102, 96, 151, 0.2)',
'rgba(10, 168, 196, 0.2)',
'rgba(102, 96, 151, 0.2)',  
'rgba(10, 168, 196, 0.2)',
'rgba(102, 96, 151, 0.2)'       
        ],
        borderColor: [
'rgba(10, 168, 196, 1)',
'rgba(102, 96, 151, 1)',
'rgba(10, 168, 196, 1)',
'rgba(102, 96, 151, 1)',
'rgba(10, 168, 196, 1)',
'rgba(102, 96, 151, 1)'
        ],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      },
      onClick: handleClick
    }
  });

  window.onmessage = function(event){

    if (event.data && Array.isArray(event.data)) {
      myChart.data.datasets[0].data = event.data;
      myChart.update();
    }
    else {
      console.log("HTML Code Element received a generic message:");
      console.log(event.data);
    }
  };

  function handleClick(e){
    var activeBars = myChart.getElementAtEvent(e);

    var value = myChart.config.data.datasets[activeBars[0]._datasetIndex].data[activeBars[0]._index];
    var label = activeBars[0]._model.label;

    window.parent.postMessage({
      "type":"click",
      "label":label,
      "value":value
    } , "*");
  }

  function ready(){
    window.parent.postMessage({"type":"ready"}, "*");
  }

</script>

</body>
</html>

 

COMMENTS

I'm a paragraph. Click here to add your own text and edit me. It's easy.

No comments. Be the first to leave a comment.

This is spectacular. Thank you so much for providing this, it's greatly appreciated.

choroin

Aug 13, 2019

1

Hi Choroin, we are glad that you like our tutorials!

Andrew (Vorbly)

Aug 17, 2019

1

this is great guys :) ... I only have one question. how I change the labels dynamically based on the selection of the dropdown, I mean to show the labels with values only.
Thanks!

Liu

Sep 09, 2019

1

WEB DESIGN & DEVELOPMENT SOLUTIONS

GET PROFESSIONAL HELP