3

I would like to show a loader using the Magento's default loader widget on my ajax call. When user clicks the submit button I would like to show the loader for 1 second and then hide it.

I am using something like this :

<script>
    require([
        'jquery',
        'jquery/ui',
        'mage/loader',

    ], function ($, loader) {
        $(function () { // to ensure that code evaluates on page load

           $.ajax({
             ... 
            })
1
  • Quick tip, if a require JS file is required on page load add domReady! as a dependency rather than the jQuery function method. If you do it with a jQuery function other modules will not be aware of the page load dependency.
    – Ben Crook
    Sep 19, 2017 at 15:22

1 Answer 1

6

It's impressively simple:

 $('body').trigger('processStart');

And to remove it

$('body').trigger('processStop');

Source code can be found here.

Result:

enter image description here


Note on loading scripts after page load

Quick tip, if a require JS file is required on page load add domReady! as a dependency rather than the jQuery function method. If you do it with a jQuery function other modules will not be aware of the page load dependency.

7
  • Thanks for the answer. Is this assuming I did $('body').loader() before? .
    – faniva
    Sep 19, 2017 at 16:04
  • Nope, I just tested it out in one of my JS files that has never used the loader before. I didn't even need to load it as a dependency. I'm impressed.
    – Ben Crook
    Sep 19, 2017 at 16:09
  • I believe the JS is already initialised in vendor/magento/module-theme/view/base/templates/root.phtml as it contains data-mage-init='{"loaderAjax": {}... on the body tag.
    – Ben Crook
    Sep 19, 2017 at 16:10
  • If the answer works for you please mark it as accepted, internet points ftw
    – Ben Crook
    Sep 19, 2017 at 16:11
  • 1
    Weirdly , this didn't work for me. But this did: $('body').loader({}); $('body').loader('show'); @BenCrook
    – faniva
    Sep 19, 2017 at 16:19

Your Answer

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

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