Magento 2.3.4 – Refresh window.checkoutConfig

checkoutjavascriptknockoutjsmagento2.3PHP

We are adding shipping price of quote object to myTestData which is pulled onto the page using window.checkoutConfig.myTestData:

use Magento\Checkout\Model\ConfigProviderInterface;

class Config implements ConfigProviderInterface
{
  protected $checkoutSession;

  public function __construct(
    \Magento\Checkout\Model\Session $checkoutSession
  ) {
    $this->checkoutSession = $checkoutSession;
  }

  /* Get Quote */
  public function getQuote()
  {
    return $this->checkoutSession->getQuote();
  }

  /* Return Config Details */
  public function getConfig()
  {
    $config = [];
    $config['myTestData'] = $this->getQuote()->getShippingAddress()->getShippingAmount();

    return $config;
  }

This returns the proper shipping amount on first load of the cart, but if we change shipping method, myTestData does not get updated to reflect the new value. How can we make sure window.checkoutConfig.myTestData gets refreshed if / when cart is updated?

EDIT, if not using checkoutConfig, is there another way to pass dynamic block variables to javascript object any time the cart updates?

Best Answer

PHP functions run when page is reload so you can do this in you custom controller what ever you want

steps

  1. create a ajax call on shipping select to a controller

like on shipping select radio button add

onlick="myfunction()"

and in js file use like this

   function myfunction() {
    jQuery.ajax({
        url: '/routename/controller_folder/controller_file',
        type: 'POST',
        dataType: 'json',
        data: {
            yourvariable: your_variable_value
        },
        complete: function(response) {

        }
    });
}
  1. in your controller get that value in execute function like

    $yourvariable = $this->getRequest()->getParam('yourvariable');

now do what ever you like with this variable

By this when ever the shipping method changes it will call that ajax with updated JS variable

hope you get my point if need more details feel free to comment if helps then up-vote please

Related Topic