<p>In <b>Prototype</b> I can show a "loading..." image with this code:</p>

<pre><code>var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, 
onLoading: showLoad, onComplete: showResponse} );

function showLoad () {
    ...
}
</code></pre>

<p>In <b>jQuery</b>, I can load a server page into an element with this:</p>

<pre><code>$('#message').load('index.php?pg=ajaxFlashcard');
</code></pre>

<p>but how do I attach a loading spinner to this command as I did in Prototype?</p>

[{'answer_id': 68503, 'author': 'nickf', 'author_id': 9021, 'author_profile': 'https://Stackoverflow.com/users/9021', 'pm_score': 11, 'selected': True, 'text': "<p>There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.</p>\n\n<pre><code>$('#loadingDiv')\n    .hide()  // Hide it initially\n    .ajaxStart(function() {\n        $(this).show();\n    })\n    .ajaxStop(function() {\n        $(this).hide();\n    })\n;\n</code></pre>\n\n<p>The ajaxStart/Stop functions will fire whenever you do any Ajax calls.</p>\n\n<p><strong>Update</strong>: As of jQuery 1.8, the documentation states that <code>.ajaxStart/Stop</code> should only be attached to <code>document</code>. This would transform the above snippet to:</p>\n\n<pre><code>var $loading = $('#loadingDiv').hide();\n$(document)\n  .ajaxStart(function () {\n    $loading.show();\n  })\n  .ajaxStop(function () {\n    $loading.hide();\n  });\n</code></pre>\n"}, {'answer_id': 68517, 'author': 'Brent', 'author_id': 10680, 'author_profile': 'https://Stackoverflow.com/users/10680', 'pm_score': 4, 'selected': False, 'text': '<pre><code>$(\'#message\').load(\'index.php?pg=ajaxFlashcard\', null, showResponse);\nshowLoad();\n\nfunction showResponse() {\n    hideLoad();\n    ...\n}\n</code></pre>\n\n<p><a href="http://docs.jquery.com/Ajax/load#urldatacallback" rel="noreferrer">http://docs.jquery.com/Ajax/load#urldatacallback</a></p>\n'}, {'answer_id': 68546, 'author': 'Josh Stodola', 'author_id': 54420, 'author_profile': 'https://Stackoverflow.com/users/54420', 'pm_score': 5, 'selected': False, 'text': '<p>You can insert the animated image into the DOM right before the AJAX call, and do an inline function to remove it...</p>\n\n<pre><code>$("#myDiv").html(\'&lt;img src="images/spinner.gif" alt="Wait" /&gt;\');\n$(\'#message\').load(\'index.php?pg=ajaxFlashcard\', null, function() {\n  $("#myDiv").html(\'\');\n});\n</code></pre>\n\n<p>This will make sure your animation starts at the same frame on subsequent requests (if that matters). Note that old versions of IE <em>might</em> have difficulties with the animation.</p>\n\n<p>Good luck!</p>\n'}, {'answer_id': 238563, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<h3>JavaScript</h3>\n\n<pre><code>$.listen(\'click\', \'#captcha\', function() {\n    $(\'#captcha-block\').html(\'&lt;div id="loading" style="width: 70px; height: 40px; display: inline-block;" /&gt;\');\n    $.get("/captcha/new", null, function(data) {\n        $(\'#captcha-block\').html(data);\n    }); \n    return false;\n});\n</code></pre>\n\n<h3>CSS</h3>\n\n<pre><code>#loading { background: url(/image/loading.gif) no-repeat center; }\n</code></pre>\n'}, {'answer_id': 1201403, 'author': 'Nathan Bubna', 'author_id': 8131, 'author_profile': 'https://Stackoverflow.com/users/8131', 'pm_score': 4, 'selected': False, 'text': '<p>Use the loading plugin:  <a href="http://plugins.jquery.com/project/loading" rel="nofollow noreferrer">http://plugins.jquery.com/project/loading</a></p>\n\n<pre><code>$.loading.onAjax({img:\'loading.gif\'});\n</code></pre>\n'}, {'answer_id': 2387709, 'author': 'kr00lix', 'author_id': 183887, 'author_profile': 'https://Stackoverflow.com/users/183887', 'pm_score': 8, 'selected': False, 'text': "<p>For jQuery I use</p>\n\n<pre><code>jQuery.ajaxSetup({\n  beforeSend: function() {\n     $('#loader').show();\n  },\n  complete: function(){\n     $('#loader').hide();\n  },\n  success: function() {}\n});\n</code></pre>\n"}, {'answer_id': 5863245, 'author': 'Paul', 'author_id': 735217, 'author_profile': 'https://Stackoverflow.com/users/735217', 'pm_score': 3, 'selected': False, 'text': '<p>Variant: I have an icon with id="logo" at the top left of the main page; a spinner gif is then overlaid on top (with transparency) when ajax is working.</p>\n\n<pre><code>jQuery.ajaxSetup({\n  beforeSend: function() {\n     $(\'#logo\').css(\'background\', \'url(images/ajax-loader.gif) no-repeat\')\n  },\n  complete: function(){\n     $(\'#logo\').css(\'background\', \'none\')\n  },\n  success: function() {}\n});\n</code></pre>\n'}, {'answer_id': 7389431, 'author': 'Umesh kumar', 'author_id': 940764, 'author_profile': 'https://Stackoverflow.com/users/940764', 'pm_score': 3, 'selected': False, 'text': '<p>You can simply assign a loader image to the same tag on which you later will load content using an Ajax call:</p>\n\n<pre><code>$("#message").html(\'&lt;span&gt;Loading...&lt;/span&gt;\');\n\n$(\'#message\').load(\'index.php?pg=ajaxFlashcard\');\n</code></pre>\n\n<p>You can also replace the span tag with an image tag.</p>\n'}, {'answer_id': 7597533, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>I do this:</p>\n\n<pre><code>var preloaderdiv = \'&lt;div class="thumbs_preloader"&gt;Loading...&lt;/div&gt;\';\n           $(\'#detail_thumbnails\').html(preloaderdiv);\n             $.ajax({\n                        async:true,\n                        url:\'./Ajaxification/getRandomUser?top=\'+ $(sender).css(\'top\') +\'&amp;lef=\'+ $(sender).css(\'left\'),\n                        success:function(data){\n                            $(\'#detail_thumbnails\').html(data);\n                        }\n             });\n</code></pre>\n'}, {'answer_id': 8360518, 'author': 'Quinn Comendant', 'author_id': 277303, 'author_profile': 'https://Stackoverflow.com/users/277303', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve used the following with jQuery UI Dialog. (Maybe it works with other ajax callbacks?)</p>\n\n<pre><code>$(\'&lt;div&gt;&lt;img src="/i/loading.gif" id="loading" /&gt;&lt;/div&gt;\').load(\'/ajax.html\').dialog({\n    height: 300,\n    width: 600,\n    title: \'Wait for it...\'\n});\n</code></pre>\n\n<p>The  contains an animated loading gif until its content is replaced when the ajax call completes.</p>\n'}, {'answer_id': 11454964, 'author': 'guy mograbi', 'author_id': 1068746, 'author_profile': 'https://Stackoverflow.com/users/1068746', 'pm_score': 1, 'selected': False, 'text': '<p>I think you are right. \nThis method is too global... </p>\n\n<p>However - it is a good default for when your AJAX call has no effect on the page itself. (background save for example). ( you can always switch it off for a certain ajax call by passing "global":false - see documentation at <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow">jquery</a> </p>\n\n<p>When the AJAX call is meant to refresh part of the page,  I like my "loading" images to be specific to the refreshed section. I would like to see which part is refreshed. </p>\n\n<p>Imagine how cool it would be if you could simply write something like : </p>\n\n<pre><code>$("#component_to_refresh").ajax( { ... } ); \n</code></pre>\n\n<p>And this would show a "loading" on this section. \nBelow is a function I wrote that handles "loading" display as well but it is specific to the area you are refreshing in ajax. </p>\n\n<p>First, let me show you how to use it </p>\n\n<pre><code>&lt;!-- assume you have this HTML and you would like to refresh \n      it / load the content with ajax --&gt;\n\n&lt;span id="email" name="name" class="ajax-loading"&gt;\n&lt;/span&gt;\n\n&lt;!-- then you have the following javascript --&gt; \n\n$(document).ready(function(){\n     $("#email").ajax({\'url\':"/my/url", load:true, global:false});\n })\n</code></pre>\n\n<p>And this is the function - a basic start that you can enhance as you wish. it is very flexible. </p>\n\n<pre><code>jQuery.fn.ajax = function(options)\n{\n    var $this = $(this);\n    debugger;\n    function invokeFunc(func, arguments)\n    {\n        if ( typeof(func) == "function")\n        {\n            func( arguments ) ;\n        }\n    }\n\n    function _think( obj, think )\n    {\n        if ( think )\n        {\n            obj.html(\'&lt;div class="loading" style="background: url(/public/images/loading_1.gif) no-repeat; display:inline-block; width:70px; height:30px; padding-left:25px;"&gt; Loading ... &lt;/div&gt;\');\n        }\n        else\n        {\n            obj.find(".loading").hide();\n        }\n    }\n\n    function makeMeThink( think )\n    {\n        if ( $this.is(".ajax-loading") )\n        {\n            _think($this,think);\n        }\n        else\n        {\n            _think($this, think);\n        }\n    }\n\n    options = $.extend({}, options); // make options not null - ridiculous, but still.\n    // read more about ajax events\n    var newoptions = $.extend({\n        beforeSend: function()\n        {\n            invokeFunc(options.beforeSend, null);\n            makeMeThink(true);\n        },\n\n        complete: function()\n        {\n            invokeFunc(options.complete);\n            makeMeThink(false);\n        },\n        success:function(result)\n        {\n            invokeFunc(options.success);\n            if ( options.load )\n            {\n                $this.html(result);\n            }\n        }\n\n    }, options);\n\n    $.ajax(newoptions);\n};\n</code></pre>\n'}, {'answer_id': 12190482, 'author': 'Seeker', 'author_id': 468202, 'author_profile': 'https://Stackoverflow.com/users/468202', 'pm_score': 6, 'selected': False, 'text': '<p>You can just use the jQuery\'s <code>.ajax</code> function and use its option <code>beforeSend</code> and define some function in which you can show something like a loader div and on success option you can hide that loader div.</p>\n\n<pre><code>jQuery.ajax({\n    type: "POST",\n    url: \'YOU_URL_TO_WHICH_DATA_SEND\',\n    data:\'YOUR_DATA_TO_SEND\',\n    beforeSend: function() {\n        $("#loaderDiv").show();\n    },\n    success: function(data) {\n        $("#loaderDiv").hide();\n    }\n});\n</code></pre>\n\n<p>You can have any Spinning Gif image. Here is a website that is a great AJAX Loader Generator according to your color scheme: <a href="http://ajaxload.info/" rel="noreferrer">http://ajaxload.info/</a></p>\n'}, {'answer_id': 12268009, 'author': 'Lee Goddard', 'author_id': 418150, 'author_profile': 'https://Stackoverflow.com/users/418150', 'pm_score': 3, 'selected': False, 'text': "<p>As well as setting global defaults for ajax events, you can set behaviour for specific elements. Perhaps just changing their class would be enough?</p>\n\n<pre><code>$('#myForm').ajaxSend( function() {\n    $(this).addClass('loading');\n});\n$('#myForm').ajaxComplete( function(){\n    $(this).removeClass('loading');\n});\n</code></pre>\n\n<p>Example CSS, to hide #myForm with a spinner:</p>\n\n<pre><code>.loading {\n    display: block;\n    background: url(spinner.gif) no-repeat center middle;\n    width: 124px;\n    height: 124px;\n    margin: 0 auto;\n}\n/* Hide all the children of the 'loading' element */\n.loading * {\n    display: none;  \n}\n</code></pre>\n"}, {'answer_id': 15763341, 'author': 'Emil Stenström', 'author_id': 117268, 'author_profile': 'https://Stackoverflow.com/users/117268', 'pm_score': 3, 'selected': False, 'text': '<p>I ended up with two changes to the <a href="https://stackoverflow.com/a/68503/117268">original reply</a>. </p>\n\n<ol>\n<li>As of jQuery 1.8, ajaxStart and ajaxStop should only be attached to <code>document</code>. This makes it harder to filter only a some of the ajax requests. Soo...</li>\n<li>Switching to <a href="http://api.jquery.com/ajaxSend/" rel="nofollow noreferrer">ajaxSend</a> and <a href="http://api.jquery.com/ajaxComplete/" rel="nofollow noreferrer">ajaxComplete</a> makes it possible to interspect the current ajax request before showing the spinner.</li>\n</ol>\n\n<p>This is the code after these changes:</p>\n\n<pre><code>$(document)\n    .hide()  // hide it initially\n    .ajaxSend(function(event, jqxhr, settings) {\n        if (settings.url !== "ajax/request.php") return;\n        $(".spinner").show();\n    })\n    .ajaxComplete(function(event, jqxhr, settings) {\n        if (settings.url !== "ajax/request.php") return;\n        $(".spinner").hide();\n    })\n</code></pre>\n'}, {'answer_id': 15907031, 'author': 'keithhackbarth', 'author_id': 965679, 'author_profile': 'https://Stackoverflow.com/users/965679', 'pm_score': 1, 'selected': False, 'text': '<p>If you don\'t want to write your own code, there are also a lot of plugins that do just that:</p>\n\n<ul>\n<li><a href="https://github.com/keithhackbarth/jquery-loading" rel="nofollow">https://github.com/keithhackbarth/jquery-loading</a></li>\n<li><a href="http://plugins.jquery.com/project/loading" rel="nofollow">http://plugins.jquery.com/project/loading</a></li>\n</ul>\n'}, {'answer_id': 16938360, 'author': 'Amin Saqi', 'author_id': 1814343, 'author_profile': 'https://Stackoverflow.com/users/1814343', 'pm_score': 5, 'selected': False, 'text': '<p>If you are using <code>$.ajax()</code> you can use somthing like this:</p>\n<pre><code>$.ajax({\n  url: &quot;destination url&quot;,\n  success: sdialog,\n  error: edialog,\n  // shows the loader element before sending.\n  beforeSend: function() {\n    $(&quot;#imgSpinner1&quot;).show();\n  },\n  // hides the loader after completion of request, whether successfull or failor.             \n  complete: function() {\n    $(&quot;#imgSpinner1&quot;).hide();\n  },\n  type: \'POST\',\n  dataType: \'json\'\n});\n</code></pre>\n<p>Although the setting is named &quot;beforeSend&quot;, as of <a href="https://api.jquery.com/jQuery.ajax/" rel="noreferrer">jQuery 1.5 &quot;beforeSend&quot; will be called regardless of the request type.</a> i.e. The <code>.show()</code> function will be called if <code>type: \'GET\'</code>.</p>\n'}, {'answer_id': 19910389, 'author': 'Fred K', 'author_id': 1252920, 'author_profile': 'https://Stackoverflow.com/users/1252920', 'pm_score': 2, 'selected': False, 'text': '<p>This is the best way for me:</p>\n\n<p><strong>jQuery</strong>:</p>\n\n<pre><code>$(document).ajaxStart(function() {\n  $(".loading").show();\n});\n\n$(document).ajaxStop(function() {\n  $(".loading").hide();\n});\n</code></pre>\n\n<p><strong>Coffee</strong>:</p>\n\n<pre><code>  $(document).ajaxStart -&gt;\n    $(".loading").show()\n\n  $(document).ajaxStop -&gt;\n    $(".loading").hide()\n</code></pre>\n\n<p>Docs: <a href="http://api.jquery.com/ajaxStart/" rel="nofollow">ajaxStart</a>, <a href="http://api.jquery.com/ajaxStop/" rel="nofollow">ajaxStop</a></p>\n'}, {'answer_id': 21930015, 'author': 'Brendan Vogt', 'author_id': 225799, 'author_profile': 'https://Stackoverflow.com/users/225799', 'pm_score': 3, 'selected': False, 'text': '<p>I also want to contribute to this answer. I was looking for something similar in jQuery and this what I eventually ended up using.</p>\n\n<p>I got my loading spinner from <a href="http://ajaxload.info/" rel="noreferrer">http://ajaxload.info/</a>. My solution is based on this simple answer at <a href="http://christierney.com/2011/03/23/global-ajax-loading-spinners/" rel="noreferrer">http://christierney.com/2011/03/23/global-ajax-loading-spinners/</a>.</p>\n\n<p>Basically your HTML markup and CSS would look like this:</p>\n\n<pre><code>&lt;style&gt;\n     #ajaxSpinnerImage {\n          display: none;\n     }\n&lt;/style&gt;\n\n&lt;div id="ajaxSpinnerContainer"&gt;\n     &lt;img src="~/Content/ajax-loader.gif" id="ajaxSpinnerImage" title="working..." /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>And then you code for jQuery would look something like this:</p>\n\n<pre><code>&lt;script&gt;\n     $(document).ready(function () {\n          $(document)\n          .ajaxStart(function () {\n               $("#ajaxSpinnerImage").show();\n          })\n          .ajaxStop(function () {\n               $("#ajaxSpinnerImage").hide();\n          });\n\n          var owmAPI = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&amp;APPID=YourAppID";\n          $.getJSON(owmAPI)\n          .done(function (data) {\n               alert(data.coord.lon);\n          })\n          .fail(function () {\n               alert(\'error\');\n          });\n     });\n&lt;/script&gt;\n</code></pre>\n\n<p>It is as simple as that :)</p>\n'}, {'answer_id': 26523067, 'author': 'Shane Rowatt', 'author_id': 1273319, 'author_profile': 'https://Stackoverflow.com/users/1273319', 'pm_score': 2, 'selected': False, 'text': "<p>Note that you must use asynchronous calls for spinners to work (at least that is what caused mine to not show until after the ajax call and then swiftly went away as the call had finished and removed the spinner).</p>\n\n<pre><code>$.ajax({\n        url: requestUrl,\n        data: data,\n        dataType: 'JSON',\n        processData: false,\n        type: requestMethod,\n        async: true,                         &lt;&lt;&lt;&lt;&lt;&lt;------ set async to true\n        accepts: 'application/json',\n        contentType: 'application/json',\n        success: function (restResponse) {\n            // something here\n        },\n        error: function (restResponse) {\n            // something here                \n        }\n    });\n</code></pre>\n"}, {'answer_id': 35783093, 'author': 'ling', 'author_id': 405042, 'author_profile': 'https://Stackoverflow.com/users/405042', 'pm_score': 1, 'selected': False, 'text': '<p>If you plan to use a loader everytime you make a server request, you can use the following pattern.</p>\n\n<pre><code> jTarget.ajaxloader(); // (re)start the loader\n $.post(\'/libs/jajaxloader/demo/service/service.php\', function (content) {\n     jTarget.append(content); // or do something with the content\n })\n .always(function () {\n     jTarget.ajaxloader("stop");\n });\n</code></pre>\n\n<p>This code in particular uses the jajaxloader plugin (which I just created)</p>\n\n<p><a href="https://github.com/lingtalfi/JAjaxLoader/" rel="nofollow">https://github.com/lingtalfi/JAjaxLoader/</a></p>\n'}, {'answer_id': 39982956, 'author': 'Izabela Skibinska', 'author_id': 2176086, 'author_profile': 'https://Stackoverflow.com/users/2176086', 'pm_score': 2, 'selected': False, 'text': '<pre><code>$(\'#loading-image\').html(\'&lt;img src="/images/ajax-loader.gif"&gt; Sending...\');\n\n        $.ajax({\n            url:  uri,\n            cache: false,\n            success: function(){\n                $(\'#loading-image\').html(\'\');           \n            },\n\n           error:   function(jqXHR, textStatus, errorThrown) {\n            var text =  "Error has occured when submitting the job: "+jqXHR.status+ " Contact IT dept";\n           $(\'#loading-image\').html(\'&lt;span style="color:red"&gt;\'+text +\'  &lt;/span&gt;\');\n\n            }\n        });\n</code></pre>\n'}, {'answer_id': 41000442, 'author': 'andcl', 'author_id': 3099449, 'author_profile': 'https://Stackoverflow.com/users/3099449', 'pm_score': 2, 'selected': False, 'text': '<p>This is a very simple and smart plugin for that specific purpose:\n<a href="https://github.com/hekigan/is-loading" rel="nofollow noreferrer">https://github.com/hekigan/is-loading</a></p>\n'}, {'answer_id': 45696924, 'author': 'SamyCode', 'author_id': 2770633, 'author_profile': 'https://Stackoverflow.com/users/2770633', 'pm_score': 0, 'selected': False, 'text': '<p>You can always use <a href="http://malsup.com/jquery/block/#overview" rel="nofollow noreferrer">Block UI jQuery plugin</a> which does everything for you, and it even blocks the page of any input while the ajax is loading. In case that the plugin seems to not been working, you can read about the right way to use it <a href="https://stackoverflow.com/questions/29796115/jquery-blockui-not-working">in this answer.</a> Check it out.</p>\n'}, {'answer_id': 50678783, 'author': 'Jaggan_j', 'author_id': 2093481, 'author_profile': 'https://Stackoverflow.com/users/2093481', 'pm_score': 1, 'selected': False, 'text': '<p>My ajax code looks like this, in effect, I have just commented out async: false line and the spinner shows up.</p>\n\n<pre><code>$.ajax({\n        url: "@Url.Action("MyJsonAction", "Home")",\n        type: "POST",\n        dataType: "json",\n        data: {parameter:variable},\n        //async: false, \n\n        error: function () {\n        },\n\n        success: function (data) {\n          if (Object.keys(data).length &gt; 0) {\n          //use data \n          }\n          $(\'#ajaxspinner\').hide();\n        }\n      });\n</code></pre>\n\n<p>I am showing the spinner within a function before the ajax code:</p>\n\n<pre><code>$("#MyDropDownID").change(function () {\n        $(\'#ajaxspinner\').show();\n</code></pre>\n\n<p>For Html, I have used a font awesome class:</p>\n\n<p><code>&lt;i id="ajaxspinner" class="fas fa-spinner fa-spin fa-3x fa-fw" style="display:none"&gt;&lt;/i&gt;</code></p>\n\n<p>Hope it helps someone.</p>\n'}, {'answer_id': 72977140, 'author': 'Ravi Sharma', 'author_id': 11027707, 'author_profile': 'https://Stackoverflow.com/users/11027707', 'pm_score': 0, 'selected': False, 'text': "<pre><code>&lt;script&gt;\n                $(window).on('beforeunload', function (e) {\n                    $(&quot;#loader&quot;).show();\n                });\n                $(document).ready(function () {\n                    $(window).load(function () {\n                        $(&quot;#loader&quot;).hide();\n                    });\n                });\n            &lt;/script&gt;\n\n&lt;div id=&quot;loader&quot;&gt;\n                    &lt;img src=&quot;../images/loader.png&quot; \n                         style=&quot;width:90px;&quot;&gt;\n                &lt;/div&gt;\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/68485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4639/']