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…