I am doing a little exercise with Laravel 8 to convert currencies using https://www.currencyconverterapi.com/ as an API, I encounter the following problem when receiving the json in the front after making the request.
This is the ajax function I am using to make the request:
$("#submit").click(function (e) {
e.preventDefault();
let toCurrency = $('#to_currency').val();
let fromCurrency = $('#from_currency').val();
let amount = $('#amount').val();
let token = '{{csrf_token()}}';
let data={
toCurrency:toCurrency,
fromCurrency:fromCurrency,
amount:amount
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "post",
url: "{{ route('exchange.currency') }}",
data: data,
success: function (data) {
console.log(data);
}
});
});
When the backend responds the json arrives incomplete
Example:
{
"amount": "10000.00",
"toCurrency": "",
"fromCurrency": ""
But if I remove the ajax function and make the request through the submit button, the json arrives complete:
{
"amount": "18.36",
"toCurrency": "USD",
"fromCurrency": "PHP"
This is the function I have inside the controller in Laravel:
public function exchangeCurrency(Request $request)
{
//Key from https://free.currencyconverterapi.com/
$apikey = '*****************';
$from_Currency = urlencode($request->from_currency);
$to_Currency = urlencode($request->to_currency);
$amount = $request->amount;
$query = "{$from_Currency}_{$to_Currency}";
$json = file_get_contents("https://free.currconv.com/api/v7/convert?q={$query}&compact=ultra&apiKey={$apikey}");
$obj = json_decode($json, true);
$val = floatval($obj["$query"]);
$total = $val * $amount;
$total= number_format($total, 2, '.', '');
$data = [
'amount' => $total,
'fromCurrency' => $from_Currency,
'toCurrency' => $to_Currency,
];
return response()->json($data,200);
}
EDIT
HTML form code:
<form action="#" method="post">
<label for="amount">Amout</label>
<input type="text" name="amount" id="amount">
<label for="">From:</label>
<select class="" id="from_currency" name="from_currency">
<option value="USD">USD</option>
<option value="PHP">PHP</option>
<option value="EUR">EUR</option>
</select>
<label for="">To:</label>
<select class="" data-flag="true" id="to_currency" name="to_currency">
<option value="USD">USD</option>
<option value="PHP">PHP</option>
<option value="EUR">EUR</option>
</select><br>
<input type="submit" id="submit" value="Convertir">
</form>