0

I am new to magento 2. I want to send the day and time option selected by user at checkout to my Controller. When the user selects a day and time slot from the dropdown, it gets the value but I do not know how to send it to my Controller.

Following are my files.

.js file

define(
    [
        'ko',
        'uiComponent',
        'underscore',
        'Magento_Checkout/js/model/step-navigator',
        'Magento_Customer/js/model/customer'
    ],
    function (
        ko,
        Component,
        _,
        stepNavigator,
        customer
    ) {
        'use strict';
        /**
         * check-login - is the name of the component's .html template
         */
        let date = window.checkoutConfig.a4date;
        let latestTime;
        let latestDate;
        let dateValues = date.toString().split(",");
        if (dateValues[0] === '') {
            dateValues = [];
            dateValues.push('Tuesday');
        }
        console.log(dateValues);

        let time = window.checkoutConfig.a4time;
        let timeValues = time.toString().split(",");
        if (timeValues[0] === '') {
            timeValues = [];
            timeValues.push('13:00-16:00');
        }
        console.log(timeValues);


        return Component.extend({
            defaults: {
                template: 'A4_CustomDelivery/check-login'
            },

            //add here your logic to display step,
            isVisible: ko.observable(true),
            isLogedIn: customer.isLoggedIn(),
            //step code will be used as step content id in the component template
            stepCode: 'isLogedCheck',
            //step title value
            stepTitle: 'Delivery Date & Time',

            /**
             *
             * @returns {*}
             */
            initialize: function () {
                this._super();
                // register your step
                stepNavigator.registerStep(
                    this.stepCode,
                    //step alias
                    null,
                    this.stepTitle,
                    //observable property with logic when display step or hide step
                    this.isVisible,

                    _.bind(this.navigate, this),

                    /**
                     * sort order value
                     * 'sort order value' < 10: step displays before shipping step;
                     * 10 < 'sort order value' < 20 : step displays between shipping and payment step
                     * 'sort order value' > 20 : step displays after payment step
                     */
                    15
                );

                return this;
            },

            /**
             * The navigate() method is responsible for navigation between checkout step
             * during checkout. You can add custom logic, for example some conditions
             * for switching to your custom step
             */
            navigate: function () {

            },

            /**
             * @returns void
             */
            navigateToNextStep: function () {
                stepNavigator.next();
                latestTime = this.chosenTime._latestValue[0];
                latestDate = this.chosenDate._latestValue[0];
                console.log(latestDate);
                console.log(latestTime);
            },






            chosenDate : ko.observableArray([dateValues[0]]),
            availableDates : ko.observableArray(
                (dateValues)
            ),
            getDate:function (data, event) {
                //console.log(this.chosenDate());
            },



            chosenTime : ko.observableArray([timeValues[0]]),
            availableTimes : ko.observableArray(
                (timeValues)
            ),
            getTime:function (data, event) {
                //console.log(this.chosenTime());
            },




            transfer : function() {
                const Http = new XMLHttpRequest();
                const str = 'day='+ latestTime + '&time=' + latestDate;
                console.log(latestTime + latestDate);
                const url='http://new_key/dateandtime/index/placeorder?' + str;
                Http.open("GET", url);
                Http.send();

                Http.onreadystatechange = (e) => {
                    alert('ok');
                    console.log("muizzzzz");
                    console.log(latestTime + latestDate);
                    console.log(Http.responseText);
                }
            },
        });
    }
)

I need to send latestDate and latestTime values to my Controller so I can use the data there.

Controller file

<?php

declare(strict_types=1);

namespace A4\CustomDelivery\Controller\Index;

use Magento\Framework\App\ActionInterface;
use Magento\Framework\Controller\Result\RawFactory;

class placeorder extends \Magento\Framework\App\Action\Action
{
    protected \Magento\Framework\View\Result\PageFactory $resultPageFactory;
    protected $customerSession;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        echo "hi";
        exit();
        //return $this->resultPageFactory->create();
    }
}

Instead of echoing 'hi', I need to echo the latestDate and latestTime values here. I think these are the 2 main files needed to send the variable value. If any other file is required, you can ask and I will upload that as well. Thanks!

1 Answer 1

1

I wrote a public module that you can find here: Simple ajax call with Magento

Although this module is old, it shows what seems to be missing in your code.

the code is more basic than your code as you are using uiComponents (rightly so) and I am not using component in this example.

the core of my answer is twofold:

  • if you looks at the javascript file, it shows you that your post ajax call needs to have a body with a form key and some parameters so that you can fulfil your customisation.

  • the controller shows you how to make your controller to read the custom parameters and how to returns a json response

    define([ "jquery" ], function ($) { 'use strict'; return function(config, element) { $("#click_me").on('click', function (e) { var self = this; e.preventDefault();

          $.ajax({
              type: 'post',
              url: config.ajaxUrl,
              data: {
                  test: 'a value to post',
                  form_key: $.cookie('form_key')
              },
              dataType: 'json',
              cache: false,
    
              beforeSend: function () {
                  $('body').trigger('processStart');
              },
              success: function (res) {
                  console.log('success', res.message);
    
                  $('body').trigger('processStop');
              }
          });
      });
    

    }

    });

      class Index extends \Magento\Framework\App\Action\Action implements HttpPostActionInterface
      {
          /**
           * @var \Magento\Framework\Controller\ResultFactory
           */
          private $pageFactory;
          /**
           * @var Validator
           */
          private $formKeyValidator;
    
          public function __construct(
              Context $context,
              \Magento\Framework\Controller\ResultFactory $pageFactory,
              Validator $formKeyValidator
          ) {
              parent::__construct($context);
              $this->pageFactory = $pageFactory;
              $this->formKeyValidator = $formKeyValidator;
          }
    
          /**
           * @inheritDoc
           */
          public function execute()
          {
              $resultRedirect = $this->resultRedirectFactory->create();
              if (!$this->formKeyValidator->validate($this->getRequest())) {
                  return $resultRedirect->setRefererUrl();
              }
    
              $productIds = $this->getRequest()->getParam('product_ids');
    
              $result = [
                  'success' => true,
                  'message' => 'I have been clicked by ajax'
              ];
    
              $this->getResponse()->representJson(
                  $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($result)
              );
          }
      }
    
1
  • Thank you for the answer. I will try to work around this. Commented Aug 16, 2022 at 5:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.