1

I have button on checkout page with knowckout js to find pincodes with my API. Now I want to send one ajax request to that API.

define(
    [
        'jquery',
        'ko',
        'uiComponent'
    ],
    function(
        $,
        ko,
        Component
    ) {
        'use strict';

        $(document).on('click', '.common-place-order', function (event) {

        });
    }
);

So how do we call ajax request from knockout js?

paras sakariya
  • 435
  • 5
  • 13

2 Answers2

4

Use mage/storage for ajax call in knockoutjs

You final code look like this:

define(
[
  'jquery',
  'ko',
  'uiComponent',
  'mage/storage'
],
 function(
        $,
        ko,
        Component,
        storage
    ) {
        'use strict';
    $(document).on('click', '.common-place-order', function (event) {
        /** Your function for ajax call */
        myAjaxCall: function(dataToPass) {
            fullScreenLoader.startLoader();
            storage.post(
                'url/of/mycontroller',
                JSON.stringify(dataToPass),
                true
            ).done(

            ));
        }
    });
}

);

Ali Raza
  • 203
  • 1
  • 14
Prince Patel
  • 22,708
  • 10
  • 97
  • 119
  • thanks for sharing, how can i retrieve those value returned by the function in knockout JS binding ?

    I was trying to use this

    myAjaxCall: function(dataToPass) { fullScreenLoader.startLoader(); return storage.post( 'url/of/mycontroller', JSON.stringify(dataToPass), true ).done( response

            ));
        }
    
    

    but instead of returning the response it return the whole javascript object.

    – Zeeshan Khuwaja Jun 28 '18 at 02:45
3

Try to use bellow code

define(
    [
        'jquery',
        'ko',
        'uiComponent'
    ],
    function(
        $,
        ko,
        Component
    ) {
        'use strict';

        $(document).on('click', '.common-place-order', function (event) {
        var YOUR_URL_HERE = your_ajax_url;
            var param = 'ajax=1';
                $.ajax({
                    showLoader: true,
                    url: YOUR_URL_HERE,
                    data: param,
                    type: "POST",
                    dataType: 'json'
                }).done(function (data) {
                    console.log(data);
                });
        });
    }
);

you can also use mage/storage for ajax call in knockoutjs check here

Chander Shekhar
  • 949
  • 1
  • 10
  • 25