1

I want to instantiate a loading image after submitting a form with jQuery.

I found how to do this and its working fine, but it is always for ALL jQuery requests done on the page.

Here is an example: How can I create a "Please Wait, Loading..." animation using jQuery? or here How to show loading spinner in jQuery?

Is there a way I can achieve the same effect, but only when I submit a form?

Or is there a way I can attach this to specific functions, so it only runs the "loading" image on these functions?

I have this function on a page (with other jQuery functions as well), and would like to attach the "loading" image only on this function:

 <script>
function send_temp(form) {
  jQuery.post('editor.php?bar=<?php echo $id?>', jQuery(form).serialize(),function(data) {
  jQuery('#editor').html(data);
  });
}
</script>

The function is called when I submit a form.

Thanks for any help or suggestions.

Community
  • 1
  • 1
Bolli
  • 4,714
  • 5
  • 29
  • 45
  • Is AJAX available for this particular case, or you must stick to submit? – Robson França Jan 21 '14 at 23:33
  • @RobsonFrança AJAX would be fine as well - the ideal situation would have a function I could call everytime I want the loader to appear - I just cant seams to figure out how to do it. – Bolli Jan 22 '14 at 01:14

1 Answers1

2

The other questions' answers show how to do so on page-wide basis, when AJAX is executing. You want to do it only on a form-by-form basis.

To do so with your existing code, you can use the jqXHR.always method to implement a function to the jQuery XHR object returned by jQuery.post:

function send_temp(form) {
    // Show an element containing your spinner
    $('#loadingSpinner').fadeIn();

    // Submit the form, as you were before; attach 
    jQuery.post('editor.php?bar=<?php echo $id?>', jQuery(form).serialize(),function(data) {
        jQuery('#editor').html(data);
    }).always(function(){
        // Request complete, hide the element containing your spinner
        $('#loadingSpinner').fadeOut();
    });
}

The jqXHR.always handler's callback function will be invoked when the request is complete; regardless of whether it succeeds or fails.

Jacob Budin
  • 9,136
  • 4
  • 29
  • 35
  • Thanks a lot Jakob - what does the jqXHR.always do? For some reason my POST data does not get delivered currect and the script messes op a bit. But removing the .always(function() works! So what does it do? – Bolli Jan 22 '14 at 13:06