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?

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(
                  
                ));
            }
        });
    }
);
1
  • 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. Jun 28 '18 at 2:45
2

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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