3
votes

I am trying to show loading gif image while ajax post request sends. Actually my code is capturing image via canvas and this image renders and goes to php page for saving. This php file saves and returns the image. Now I need show the loading image while request post and hide the loading image while ajax request finishes. Anyone have idea how I can do this?

JavaScript

function capture() {
    $('.showcase').html2canvas({
        onrendered: function (canvas) {
            //Set hidden field's value to image data (base-64 string)
            $('#img_val').val(canvas.toDataURL("image/png"));
            //Show loading image
            $("#preview-loading").html('<img src="editor/loader.gif" alt="Uploading...."/>');
            //Submit the form with ajax function
            $("#myForm").ajaxForm({
                target: '#preview-des'
            }).submit();
        }
    });
}

HTML

<div id="preview-loading"></div>
<div  id="preview-des"></div>
<form method="post" action="editor/save.php" enctype="multipart/form-data" id="myForm">
    <input type="hidden" name="img_val" id="img_val" value="" />
</form>
2

2 Answers

9
votes

Try to have a global method like below or make use of callbacks.

$(document).ajaxStart(function() {
    $('img').show(); // show the gif image when ajax starts
}).ajaxStop(function() {
    $('img').hide(); // hide the gif image when ajax completes
});

Have a gif image already preloaded (by default hide it)

2
votes

You can do it by ajax="true" in form and then write script for that like this

<form method="post" action="/echo/html/" ajax="true">
   <label>
      <img id="loadingimg" src="http://dev.cloudcell.co.uk/bin/loading.gif"/>   
   </label>
   <input type="submit" value="Submit" />      
</form>

set style for that

img#loadingimg{
  display: none;                   
}

script.js

$(document).ready(function(e) {
  $("form[ajax=true]").submit(function(e) {
    e.preventDefault();
    $("#loadingimg").show();
  }); 
});

Working fiddle find here : http://jsfiddle.net/clickthelink/Uwcuz/1/