Codeigniter 4 – somehow each variable is NULL when $this->request->getPost() after jQuery AJAX call

For some reason I can’t find the bug… The form’s text fields are numbers but for some reason they have a value of NULL when sent to the Controller.

this is my view:

<div class="row">
                <h1>Mortgage Calculator</h1>
                <div class="col-md-6">
                    <!-- Form start -->
                    <form id="mortgageCalculatorForm" action="<?= base_url('mortgage-calculator/calculate'); ?>" method="post">
                        <div class="mb-3">
                            <label for="loanAmount" class="form-label">Loan Amount ($)</label>
                            <input type="number" class="form-control" id="loanAmount" name="loanAmount" required>
                        </div>
                        <div class="mb-3">
                            <label for="interestRate" class="form-label">Interest Rate (%)</label>
                            <input type="number" step="0.01" class="form-control" id="interestRate" name="interestRate" required>
                        </div>
                        <div class="mb-3">
                            <label for="loanTerm" class="form-label">Loan Term (years)</label>
                            <input type="number" class="form-control" id="loanTerm" name="loanTerm" required>
                        </div>
                        <button type="submit" class="btn btn-primary">Calculate</button>
                    </form>
                </div>
                <div class="col-md-6">
                    <!-- Result output -->
                    <div class="mt-3" id="result">
                        <h4>Result</h4>
                        <p id="monthlyPayment"></p>
                        <p id="totalInterestPaid"></p>
                    </div>
                </div>

                <!-- jQuery/Javascript to update form -->
                <script>
                    $(document).ready(function() {
                        $('#mortgageCalculatorForm').on('submit', function(event) {
                            event.preventDefault();

                            const loanAmount = $('#loanAmount').val();
                            const interestRate = $('#interestRate').val();
                            const loanTerm = $('#loanTerm').val();
                            
                            $.ajax({
                                url: '<?= base_url("mortgage-calculator/calculate"); ?>', // Replace with your server endpoint
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify({
                                    loanAmount: loanAmount,
                                    interestRate: interestRate,
                                    loanTerm: loanTerm
                                }),
                                success: function(data) {
                                    $('#monthlyPayment').text(`Monthly Payment: $${data.monthlyPayment}`);
                                    $('#totalInterestPaid').text(`Total Interest Paid: $${data.totalInterestPaid}`);
                                },
                                error: function(error) {
                                    console.error('Error:', error);
                                }
                            });
                        });
                    });
                </script>
            </div>

this is my controller:

<?php

namespace AppControllers;

use AppControllersBaseController;
use CodeIgniterHTTPResponseInterface;

class MortgageCalculator extends BaseController
{
    // AJAX call to this function, returns JSON data.
    public function calculate()
    {
        // Get form data
        $loanAmount = $this->request->getPost('loanAmount');
        $interestRate = $this->request->getPost('interestRate');
        $durationYears = $this->request->getPost('loanTerm');
        
        
        var_dump($loanAmount);


        // API endpoint URL
        $apiUrl = 'https://api.api-ninjas.com/v1/mortgagecalculator?loan_amount=' . $loanAmount . '&interest_rate=' . $interestRate . '&duration_years=' . $durationYears;

        // Your API key
        $apiKey = $_SERVER['api.API_Ninjas'];

        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'X-Api-Key: ' . $apiKey
        ));

        // Execute the request
        $response = curl_exec($ch);

        // Check for cURL errors
        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            return $this->response->setJSON([
                'error' => true,
                'message' => 'Error: ' . $error
            ]);
        }

        // Close the cURL session
        curl_close($ch);

        // Decode the JSON response
        $data = json_decode($response, true);

        // Check if the API response contains the expected data
        if (isset($data['monthly_payment']['mortgage']) && isset($data['total_interest_paid']))
        {
            // Prepare the response data
            $responseData = [
                'monthlyPayment' => $data['monthly_payment']['mortgage'],
                'totalInterestPaid' => $data['total_interest_paid']
            ];

            // Return the response data as JSON
            return $this->response->setJSON($responseData);
        }
        else
        {
            // Return an error if the API response is not as expected
            return $this->response->setJSON([
                'error' => true,
                'message' => 'Invalid API response'
            ]);
        }
    }
}

I am completely baffled. It should be working but these $loanAmount, $interestRate, $durationYears, variables keep showing up as NULL…

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật