1

We have one button on checkout page to find address from our

API. We want to send one ajax request to that API to get some data.

How do we send ajax request from knockout js?

Prince Patel
  • 22,708
  • 10
  • 97
  • 119
William Holden
  • 539
  • 3
  • 7
  • 17

1 Answers1

7

Use mage/storage for ajax call in knockoutjs

define(
    [
        ...
        'mage/storage'
        ...
    ],
    function(
        ...
        storage
        ...
    ) {

        return Component.extend({
            ...

            /** Your function for ajax call */
            myAjaxCall: function(dataToPass) {

                fullScreenLoader.startLoader();
                storage.post(
                    'url/of/mycontroller',
                    JSON.stringify(dataToPass),
                    true
                ).done(
                    function (response) {
                        /** Do your code here */
                        alert('Success');
                        fullScreenLoader.stopLoader();
                    }
                ).fail(
                    function (response) {
                        fullScreenLoader.stopLoader();
                    }
                );
            }
        });
    }
);
Prince Patel
  • 22,708
  • 10
  • 97
  • 119
  • 1
    How to pass data and retrieve data in controller can you please explain – Nagendra Kodi Nov 28 '17 at 06:43
  • How can i get that data in knockout js bindng returning by this function? my ajax response i returning a string but when i use data-bind="text: myAjaxCall()" instead of printing the stirng, it print object Object. when i debug it by dumping the value of object in console.log, i can see it has the key ResponseJSON which has the string value. but i cant get it. – Zeeshan Khuwaja Jun 28 '18 at 02:50
  • Hello Prince. Do you know about which method use as beforeSend() in storage.post() ? – Rohan Hapani Sep 12 '18 at 09:46
  • How to get post data in controller while using storage ajax call? – Kishan Patadia Dec 12 '19 at 07:18
  • Getting this error: cabinet.js:19 Uncaught TypeError: Cannot read properties of undefined (reading 'post') – Jimit Bhavsar Oct 23 '21 at 06:12