Back to all projects

GST Calculator — Complete Source Code (HTML, CSS, JS, PHP)

PHP File 98 Downloads Updated: August 21, 2025
Gst Calculator
Source Code: gst-calculator.php
2,486 words, 29,152 characters
<?php
// Handle AJAX POST requests for GST calculations
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount'])) {
    header('Content-Type: application/json');

    // Get input data
    $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
    $gstRate = isset($_POST['gstRate']) ? floatval($_POST['gstRate']) : 0;
    $isInclusive = isset($_POST['isInclusive']) && $_POST['isInclusive'] === 'true';

    // Initialize response
    $response = [
        'originalAmount' => 0,
        'gstAmount' => 0,
        'totalAmount' => 0,
        'explanationHTML' => ''
    ];

    // Validate inputs
    if ($amount <= 0 || $gstRate <= 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Please enter a valid amount and GST rate']);
        exit;
    }

    // Perform calculations
    if ($isInclusive) {
        $originalAmount = $amount / (1 + ($gstRate / 100));
        $gstAmount = $amount - $originalAmount;
        $totalAmount = $amount;
        $explanationHTML = "
            <h3>GST Inclusive Calculation</h3>
            <p>In GST Inclusive mode, the entered amount includes GST.</p>
            <p><strong>Formulas:</strong></p>
            <ul>
                <li>Original Amount = Total Amount / (1 + (GST Rate / 100))</li>
                <li>GST Amount = Total Amount - Original Amount</li>
            </ul>
            <p><strong>Calculation Steps:</strong></p>
            <ul>
                <li>Step 1: Original Amount = $amount / (1 + ($gstRate / 100)) = " . number_format($originalAmount, 2) . "</li>
                <li>Step 2: GST Amount = $amount - " . number_format($originalAmount, 2) . " = " . number_format($gstAmount, 2) . "</li>
                <li>Step 3: Total Amount = $amount</li>
            </ul>
        ";
    } else {
        $originalAmount = $amount;
        $gstAmount = $amount * ($gstRate / 100);
        $totalAmount = $amount + $gstAmount;
        $explanationHTML = "
            <h3>GST Exclusive Calculation</h3>
            <p>In GST Exclusive mode, the entered amount is the base price before GST.</p>
            <p><strong>Formulas:</strong></p>
            <ul>
                <li>GST Amount = Original Amount × (GST Rate / 100)</li>
                <li>Total Amount = Original Amount + GST Amount</li>
            </ul>
            <p><strong>Calculation Steps:</strong></p>
            <ul>
                <li>Step 1: GST Amount = " . number_format($originalAmount, 2) . " × ($gstRate / 100) = " . number_format($gstAmount, 2) . "</li>
                <li>Step 2: Total Amount = " . number_format($originalAmount, 2) . " + " . number_format($gstAmount, 2) . " = " . number_format($totalAmount, 2) . "</li>
            </ul>
        ";
    }

    // Populate response
    $response['originalAmount'] = $originalAmount;
    $response['gstAmount'] = $gstAmount;
    $response['totalAmount'] = $totalAmount;
    $response['explanationHTML'] = $explanationHTML;

    // Log calculation (optional)
    error_log("GST Calculation: Amount=$amount, Rate=$gstRate, Inclusive=" . ($isInclusive ? 'true' : 'false') .
              ", Original=$originalAmount, GST=$gstAmount, Total=$totalAmount");

    // Return JSON response
    echo json_encode($response);
    exit;
}

// Default values for initial render
$defaultResults = [
    'originalAmount' => '0.00',
    'gstAmount' => '0.00',
    'totalAmount' => '0.00',
    'explanationHTML' => '<p>Please enter an amount and GST rate to calculate.</p>'
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Calculate GST easily with our user-friendly GST Calculator. Input your amount and GST rate to get instant results with a visual pie chart breakdown.">
    <title>GST Calculator</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #4361ee;
            --primary-dark: #3a0ca3;
            --primary-darker: #2c0883;
            --secondary: #7209b7;
            --accent: #f72585;
            --light: #f8f9fa;
            --light-accent: #e8eefd;
            --dark: #212529;
            --success: #4cc9f0;
            --border-radius: 16px;
            --border-radius-sm: 10px;
            --box-shadow: 0 15px 30px rgba(0,0,0,0.15);
            --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e3e8f5 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px;
            color: var(--dark);
        }
        
        .container {
            width: 100%;
            max-width: 900px;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
            margin: 20px auto;
            transform: translateY(0);
            transition: var(--transition);
        }
        
        .container:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }
        
        header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
            color: white;
            padding: 30px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        header::before {
            content: "";
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            transform: rotate(30deg);
        }
        
        h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 700;
            position: relative;
            text-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        .description {
            font-size: 1.1rem;
            opacity: 0.9;
            max-width: 600px;
            margin: 0 auto;
            position: relative;
        }
        
        .calculator-container {
            padding: 30px;
        }
        
        .tabs {
            display: flex;
            margin-bottom: 30px;
            background: var(--light);
            border-radius: var(--border-radius-sm);
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        
        .tab {
            flex: 1;
            padding: 18px;
            text-align: center;
            cursor: pointer;
            transition: var(--transition);
            font-weight: 600;
            position: relative;
            overflow: hidden;
        }
        
        .tab::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 50%;
            width: 0;
            height: 4px;
            background: var(--accent);
            transition: var(--transition);
            transform: translateX(-50%);
            border-radius: 4px 4px 0 0;
        }
        
        .tab:hover {
            background: rgba(67, 97, 238, 0.05);
        }
        
        .tab.active {
            background: rgba(67, 97, 238, 0.1);
            color: var(--primary-dark);
        }
        
        .tab.active::after {
            width: 70%;
        }
        
        .input-group {
            margin-bottom: 25px;
            position: relative;
        }
        
        label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: var(--dark);
            display: flex;
            align-items: center;
        }
        
        label i {
            margin-right: 10px;
            color: var(--primary);
        }
        
        input, select {
            width: 100%;
            padding: 18px 20px;
            border: 2px solid #e1e5ee;
            border-radius: var(--border-radius-sm);
            font-size: 16px;
            transition: var(--transition);
            background: white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        
        input:focus, select:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.1);
            transform: translateY(-2px);
        }
        
        .input-with-icon {
            position: relative;
        }
        
        .input-with-icon i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary);
        }
        
        .input-with-icon input {
            padding-left: 45px;
        }
        
        button {
            width: 100%;
            padding: 18px;
            background: linear-gradient(to right, var(--secondary), var(--accent));
            color: white;
            border: none;
            border-radius: var(--border-radius-sm);
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            margin-top: 10px;
            box-shadow: 0 5px 15px rgba(114, 9, 183, 0.3);
            position: relative;
            overflow: hidden;
        }
        
        button::before {
            content: "";
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: 0.5s;
        }
        
        button:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(114, 9, 183, 0.4);
        }
        
        button:hover::before {
            left: 100%;
        }
        
        .results {
            background: linear-gradient(135deg, var(--light-accent) 0%, #e8eefd 100%);
            padding: 25px;
            border-radius: var(--border-radius);
            margin-top: 30px;
            display: none;
            border: 1px solid rgba(67, 97, 238, 0.1);
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        
        .results.active {
            display: block;
            animation: fadeIn 0.5s ease, slideIn 0.5s ease;
        }
        
        .result-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(67, 97, 238, 0.1);
            font-size: 1.1rem;
        }
        
        .result-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
            font-weight: 700;
            font-size: 1.3rem;
            color: var(--primary-dark);
            margin-top: 10px;
            padding-top: 15px;
            border-top: 2px dashed rgba(67, 97, 238, 0.2);
        }
        
        .explanation {
            margin-bottom: 20px;
            font-size: 1rem;
            color: var(--dark);
            background: rgba(255, 255, 255, 0.5);
            padding: 15px;
            border-radius: var(--border-radius-sm);
        }
        
        .explanation h3 {
            margin-bottom: 10px;
            color: var(--primary-dark);
        }
        
        .explanation p, .explanation ul {
            margin-bottom: 10px;
        }
        
        .explanation ul {
            padding-left: 20px;
        }
        
        .chart-container {
            width: 100%;
            height: 320px;
            margin-top: 40px;
            background: white;
            border-radius: var(--border-radius);
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            border: 1px solid rgba(67, 97, 238, 0.1);
            display: none;
        }
        
        footer {
            text-align: center;
            margin-top: 40px;
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .decoration {
            position: absolute;
            width: 150px;
            height: 150px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
        }
        
        .decoration-1 {
            top: -75px;
            right: -75px;
        }
        
        .decoration-2 {
            bottom: -75px;
            left: -75px;
            width: 200px;
            height: 200px;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes slideIn {
            from { transform: translateY(20px); }
            to { transform: translateY(0); }
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.02); }
            100% { transform: scale(1); }
        }
        
        .pulse {
            animation: pulse 2s infinite;
        }
        
        @media (max-width: 768px) {
            .container {
                margin: 10px;
            }
            
            h1 {
                font-size: 2rem;
            }
            
            .calculator-container {
                padding: 20px;
            }
            
            .chart-container {
                height: 280px;
            }
            
            .result-item {
                font-size: 1rem;
            }
            
            .result-item:last-child {
                font-size: 1.2rem;
            }
            
            .explanation {
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="decoration decoration-1"></div>
            <div class="decoration decoration-2"></div>
            <h1>GST Calculator</h1>
            <p class="description">Easily calculate GST with our elegant and powerful calculator</p>
        </header>
        
        <div class="calculator-container">
            <div class="tabs">
                <div class="tab active" id="exclusive-tab">
                    <i class="fas fa-plus-circle"></i> GST Exclusive
                </div>
                <div class="tab" id="inclusive-tab">
                    <i class="fas fa-equals"></i> GST Inclusive
                </div>
            </div>
            
            <form id="gst-form">
                <div class="input-group">
                    <label for="amount"><i class="fas fa-money-bill"></i> Amount</label>
                    <div class="input-with-icon">
                        <i class="fas fa-money-bill-wave"></i>
                        <input type="number" id="amount" name="amount" placeholder="Enter amount" min="0" step="0.01" value="">
                    </div>
                </div>
                
                <div class="input-group">
                    <label for="gst-rate"><i class="fas fa-percent"></i> GST Rate</label>
                    <div class="input-with-icon">
                        <i class="fas fa-chart-line"></i>
                        <select id="gst-rate" name="gstRate">
                            <option value="5">5%</option>
                            <option value="12">12%</option>
                            <option value="18" selected>18%</option>
                            <option value="28">28%</option>
                            <option value="custom">Custom</option>
                        </select>
                    </div>
                </div>
                
                <div class="input-group" id="custom-rate-container" style="display: none;">
                    <label for="custom-rate"><i class="fas fa-cog"></i> Custom GST Rate</label>
                    <div class="input-with-icon">
                        <i class="fas fa-percent"></i>
                        <input type="number" id="custom-rate" name="customRate" placeholder="Enter custom GST rate" min="0" step="0.01" value="">
                    </div>
                </div>
                
                <button type="submit" id="calculate-btn" class="pulse">
                    <i class="fas fa-calculator"></i> Calculate GST
                </button>
            </form>
            
            <div class="results" id="results">
                <div class="explanation" id="explanation"><?php echo $defaultResults['explanationHTML']; ?></div>
                <div class="result-item">
                    <span><i class="fas fa-file-invoice-dollar"></i> Original Amount:</span>
                    <span id="original-amount"><?php echo $defaultResults['originalAmount']; ?></span>
                </div>
                <div class="result-item">
                    <span><i class="fas fa-receipt"></i> GST Amount:</span>
                    <span id="gst-amount"><?php echo $defaultResults['gstAmount']; ?></span>
                </div>
                <div class="result-item">
                    <span><i class="fas fa-money-check"></i> Total Amount:</span>
                    <span id="total-amount"><?php echo $defaultResults['totalAmount']; ?></span>
                </div>
            </div>
            
            <div class="chart-container" id="chart-container" style="display: none;">
                <canvas id="gst-chart"></canvas>
            </div>
        </div>
    </div>
    
    <footer>
        <p>©GST Calculator | Designed with <i class="fas fa-heart" style="color: var(--accent);"></i> by <a href="https://www.aviskarak.com/" target="_blank">Aviskarak.com</a></p>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Elements
            const exclusiveTab = document.getElementById('exclusive-tab');
            const inclusiveTab = document.getElementById('inclusive-tab');
            const form = document.getElementById('gst-form');
            const amountInput = document.getElementById('amount');
            const gstRateSelect = document.getElementById('gst-rate');
            const customRateContainer = document.getElementById('custom-rate-container');
            const customRateInput = document.getElementById('custom-rate');
            const resultsContainer = document.getElementById('results');
            const explanationEl = document.getElementById('explanation');
            const originalAmountEl = document.getElementById('original-amount');
            const gstAmountEl = document.getElementById('gst-amount');
            const totalAmountEl = document.getElementById('total-amount');
            const chartContainer = document.getElementById('chart-container');

            // Chart initialization
            const ctx = document.getElementById('gst-chart').getContext('2d');
            let gstChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['Original Amount', 'GST Amount'],
                    datasets: [{
                        data: [100, 0],
                        backgroundColor: ['#4361ee', '#f72585'],
                        borderWidth: 0,
                        borderRadius: 5,
                        hoverOffset: 10
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '70%',
                    plugins: {
                        legend: {
                            display: false,
                            position: 'bottom',
                            labels: {
                                font: { size: 14, family: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif" },
                                padding: 20,
                                color: '#212529',
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(33, 37, 41, 0.9)',
                            titleFont: { size: 14, family: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif" },
                            bodyFont: { size: 14, family: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif" },
                            padding: 12,
                            boxPadding: 6,
                            callbacks: {
                                label: function(context) {
                                    return context.label + ': ' + context.raw.toFixed(2);
                                }
                            }
                        },
                        datalabels: {
                            color: '#ffffff',
                            font: { size: 12, family: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif", weight: 'bold' },
                            formatter: (value) => value > 0 ? value.toFixed(2) : '',
                            anchor: 'center',
                            align: 'center'
                        }
                    }
                },
                plugins: [ChartDataLabels]
            });

            // Variables
            let isInclusive = false;

            // Event Listeners
            exclusiveTab.addEventListener('click', function() {
                exclusiveTab.classList.add('active');
                inclusiveTab.classList.remove('active');
                isInclusive = false;
                calculateGST();
            });

            inclusiveTab.addEventListener('click', function() {
                inclusiveTab.classList.add('active');
                exclusiveTab.classList.remove('active');
                isInclusive = true;
                calculateGST();
            });

            gstRateSelect.addEventListener('change', function() {
                customRateContainer.style.display = this.value === 'custom' ? 'block' : 'none';
                calculateGST();
            });

            customRateInput.addEventListener('input', calculateGST);
            amountInput.addEventListener('input', calculateGST);
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                calculateGST();
            });

            // GST Calculation Function (Server-Side)
            async function calculateGST() {
                const amount = parseFloat(amountInput.value) || 0;
                let gstRate = gstRateSelect.value === 'custom' ? (parseFloat(customRateInput.value) || 0) : parseFloat(gstRateSelect.value);

                try {
                    const data = await sendToPHP(amount, gstRate, isInclusive);
                    updateResults(data);
                } catch (error) {
                    console.warn('Server-side calculation failed:', error);
                    showError('Unable to connect to the server or invalid input. Please try again.');
                }
            }

            // Send Data to PHP
            async function sendToPHP(amount, gstRate, isInclusive) {
                const formData = new FormData();
                formData.append('amount', amount);
                formData.append('gstRate', gstRate);
                formData.append('isInclusive', isInclusive);

                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`Server error: ${response.status}`);
                }

                const data = await response.json();
                if (data.error) {
                    throw new Error(data.error);
                }

                return data;
            }

            // Update UI with Results
            function updateResults(data) {
                explanationEl.innerHTML = data.explanationHTML;
                originalAmountEl.textContent = data.originalAmount.toFixed(2);
                gstAmountEl.textContent = data.gstAmount.toFixed(2);
                totalAmountEl.textContent = data.totalAmount.toFixed(2);
                resultsContainer.classList.add('active');

                // Show chart only if valid values are received
                if (data.originalAmount > 0 || data.gstAmount > 0) {
                    chartContainer.style.display = 'block';
                    gstChart.data.datasets[0].data = [data.originalAmount, data.gstAmount];
                    gstChart.options.plugins.legend.display = true;
                    gstChart.update();
                } else {
                    chartContainer.style.display = 'none';
                }
            }

            // Display Error Message
            function showError(message) {
                explanationEl.innerHTML = `<p style="color: #dc3545; font-weight: bold;">${message}</p>`;
                originalAmountEl.textContent = '0.00';
                gstAmountEl.textContent = '0.00';
                totalAmountEl.textContent = '0.00';
                resultsContainer.classList.add('active');
                chartContainer.style.display = 'none';
                gstChart.data.datasets[0].data = [100, 0];
                gstChart.options.plugins.legend.display = false;
                gstChart.update();
            }

            // Initial state
            resultsContainer.classList.remove('active');
            chartContainer.style.display = 'none';
        });
    </script>
</body>
</html>