0

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>
yadu siva das
  • 517
  • 3
  • 12
Alee
  • 1
  • 2
  • Can you add the form HTML? Make sure the id "from_currency" and "to_currency" only exists 1 time on the page – Gert B. Jun 22 '22 at 06:08
  • I already edited the post, I hope you can help me with the error that I still can't find – Alee Jun 22 '22 at 06:17
  • So it seems that when your AJAX request happens, it does not pass from/to currency codes correctly, right? So there is some problem with the JS which gets those values. You could add some `console.log()` statements to debug this yourself. – Don't Panic Jun 22 '22 at 06:33
  • 1
    Does this answer your question? [jQuery Get Selected Option From Dropdown](https://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown) – Don't Panic Jun 22 '22 at 06:33

1 Answers1

0
  • You try add dataType in Ajax option
    • dataType: 'json' => if response return json
    • dataType: 'html' => if reponse return view
$.ajax({
        url: 'xxxx',
        'method': 'GET',
        'dataType': 'html' | 'json',
    }
......
Huy Dev
  • 26
  • 1
  • 3