/web-to-ai-ml-integrations

Integrate Charts and ML Predictions in Web App

Integrate charts & ML predictions in your web app with our step-by-step guide. Boost engagement and data insights today!

Book a free  consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Integrate Charts and ML Predictions in Web App

Integrating Machine Learning Predictions and Charts into Your Web Application

 
  • This guide explains how to connect an ML prediction API to a web front-end that displays dynamic charts. In this example, we assume you have built an ML model and expose its predictions through an API endpoint. We use a JavaScript charting library such as Chart.js to render the charts and a lightweight back-end (for example, with Python Flask) to serve predictions.
 

Step 1: Exposing the ML Prediction API

 
  • Create an API endpoint that accepts requests and returns ML predictions in JSON format. This example uses Python Flask.
  • The following code shows how to set up a basic server that receives web requests and sends back predictions.
 

// Import Flask module for web routing and JSON support
from flask import Flask, request, jsonify

app = Flask(**name**)

// Assume you have a pre-trained ML model loaded, e.g., from a pickle file
// For demonstration, we simulate a prediction function
def get_prediction(input_data):
    // Simulate a prediction logic
    prediction = sum(input_data) / len(input_data)  // e.g., calculating an average
    return prediction

// Define a route for predictions
@app.route('/predict', methods=['POST'])
def predict():
    data = request.get\_json()
    // Extract relevant data from the request JSON
    input\_data = data.get('values', [])
    
    if not input\_data:
        return jsonify({'error': 'No input data provided'}), 400

    prediction = get_prediction(input_data)
    
    // Return the prediction in JSON format
    return jsonify({'prediction': prediction})

// Run the Flask application
if **name** == '**main**':
    app.run(debug=True)

 

Step 2: Fetching ML Predictions from the Client-Side

 
  • From your web application, you need to send an HTTP POST request to the ML API endpoint and receive back the prediction results.
  • The following JavaScript snippet demonstrates how to make an AJAX call to the API using the fetch API.
 

// JavaScript code to fetch ML prediction from the API
const inputValues = [10, 20, 30, 40]; // example input for the ML model

fetch('http://localhost:5000/predict', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ values: inputValues })
})
.then(response => response.json())
.then(data => {
  // Extract prediction result from the response
  const prediction = data.prediction;
  // After receiving the prediction, feed it into the chart for visualization
  updateChart(prediction);
})
.catch(error => {
  console.error('Error fetching prediction:', error);
});

 

Step 3: Visualizing Predictions with a Chart Library

 
  • We use Chart.js as the charting library. Chart.js is a simple yet powerful open-source JavaScript tool to create charts.
  • Create a canvas element in your HTML where the chart will be rendered. Below is the example HTML markup:
 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>ML Prediction Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  </head>
  <body>
    <canvas id="predictionChart" width="400" height="200"></canvas>
    <script src="chart-script.js"></script>
  </body>
</html>

 

  • Now, add the JavaScript code to create the chart and update it with the new prediction value.
 

// Assuming this code is in 'chart-script.js'

// Initialize the chart with dummy data
const ctx = document.getElementById('predictionChart').getContext('2d');
const predictionChart = new Chart(ctx, {
  type: 'line', // or 'bar', 'pie', etc. depending on your requirements
  data: {
    labels: ['Initial'],  // X-axis labels (could represent time or categories)
    datasets: [{
      label: 'ML Prediction',
      data: [0],  // initial placeholder data
      backgroundColor: 'rgba(54, 162, 235, 0.2)', // transparency for the fill
      borderColor: 'rgba(54, 162, 235, 1)', // chart line color
      borderWidth: 1
    }]
  },
  options: {
    responsive: true,
    scales: {
      y: {
        beginAtZero: true  // ensure the y-axis starts at 0
      }
    }
  }
});

// Function to update the chart with the new prediction
function updateChart(prediction) {
  // Push new label and data point to reflect the updated prediction
  predictionChart.data.labels.push('New Prediction');
  predictionChart.data.datasets[0].data.push(prediction);
  // Re-render the chart to display updated data
  predictionChart.update();
}

 

Step 4: Integrating Real-Time Updates

 
  • If you need real-time updates, you can combine the above steps with periodic polling or web sockets.
  • For simplicity, implement periodic polling using JavaScript's setInterval function. Poll the API every few seconds and update the chart.
 

// Function to fetch prediction and update the chart periodically
function fetchAndUpdate() {
  fetch('http://localhost:5000/predict', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ values: [/_ dynamic or static input values _/] })
  })
  .then(response => response.json())
  .then(data => {
    const prediction = data.prediction;
    updateChart(prediction);
  })
  .catch(error => {
    console.error('Error during polling:', error);
  });
}

// Poll API every 5000 milliseconds (5 seconds)
setInterval(fetchAndUpdate, 5000);

 

Conclusion

 
  • This integrated approach leverages a back-end ML prediction API and a front-end charting library to display dynamic data to users.
  • You now have a complete system where a machine learning model makes predictions, which are then fetched by a web app and visualized using charts.
  • Customize the code snippets to fit your specific use-case and data format. The modular approach makes it easy to change the prediction logic or the chart type according to your needs.
 


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â