Home > Enterprise >  Set different prices according to country with response
Set different prices according to country with response

Time:10-14

I'm trying to do a onchange event with ajax and php according to country selected from a dropdown. My problem is that the response set the last price in the array on every item and I can't figure out a way to solve this. Here is my code so far:

  $("#field-organization-country-iso").on('change', (e) => {
    e.preventDefault();
    e.stopPropagation();
    const CountryIso = $('#field-organization-country-iso').val();
    Request.get(`/myrequested_file`, {
      data: { CountryIso },
    })
      .done((response) => {
    for (let i = 0; i < response.data.itemPrice.length; i  ) {
      const price = response.data.itemPrice[i];
      $('.checkout-table tr').find('.hide-if-odd-or-sub').eq(i).html(price);
    }
      });
  });

And the php-function:

public function change_currencyIso(Request $request, $summaryService): JSONResponse
{
    $countryIso = $request->query->get('CountryIso');
    $response = new JSONResponse();
    $orderSummary = $summaryService->Summary(Cart::getCurrentCart(), User::currentUserOrNull(), $countryIso, null, null);
    $items = $orderSummary->getItems();
    $currencies = new ISOCurrencies();

    $numberFormatter = new NumberFormatter(Environ::getLocale(), NumberFormatter::CURRENCY);
    $moneyFormatter = new IntlMoneyFormatter($numberFormatter, $currencies);
    $prices = [];
    foreach ($items as $item) {
        $price = $moneyFormatter->format($item->getLocalPrice());
        $prices[] = $price;
    }
    $response->setVar('itemPrice', $prices);
    return $response;
}

$prices returns the array with item prices but I know response writes over it. Can I loop through the array and add the response to each price? My response with 'itemPrice' is only returning one of the existing prices.

{itemPrice: Array(2)}
itemPrice: Array(2)
0: "245,00 US$"
1: "32,90 US$"
length: 2

Now itemPrice returns the array but still puts everything on the same row. Tried a each but that didn't help.

CodePudding user response:

You should add more details about the html structure, however I suppose you have a table with a row for each item, and the cells with the price have the class "hide-if-odd-or-sub". Also table rows are in the same order of the prices returned by the server. So, you have to assign each price to the correspondig table row:

foreach (var i in response.data.itemPrice) {
    var price = response.data.itemPrice[i];
    $('.checkout-table tr').eq(i).find('.hide-if-odd-or-sub').html(price);
}

This is not mush robust, because if the user change the items in the cart in another browser's tab and goes back to previous tab and updates the country, then the prices returned by the server won't correspond to items in the table, however it should work under normal usage.

  • Related