Adding a loading image to a jquery ajax post

leora picture leora · Feb 28, 2010 · Viewed 20.3k times · Source

i have the following javascript to post a form through ajax without refreshing the screen. Since the post take a little while, i wanted to add a loading image during processing.

I see this article but it seems to only list .load() or .get() but not $.post.

<script type="text/javascript">
    $(document).ready(function() {
        $('#contact form').live('submit', function() {

            $.post($(this).attr('action'), $(this).serialize(), function(data) {

                $("#contact").replaceWith($(data));

            });
            return false;
        });
    });
</script>

Answer

Nick Craver picture Nick Craver · Feb 28, 2010

Just add a few calls to hide/show your load screen/div, whatever:

<script type="text/javascript">
    $(function() {
        $('#contact form').live('submit', function() {
            $("#Loading").fadeIn(); //show when submitting
            $.post($(this).attr('action'), $(this).serialize(), function(data) {
                $("#contact").replaceWith($(data));
                $("#Loading").fadeOut('fast'); //hide when data's ready
            });
            return false;
        });
    });
</script>

<div id="Loading">I'm loading, image here, whatever you want</div>