Search code examples
jqueryjquery-deferredjquery-blockui

Block Screen does not work with multiple AJAX calls


I have a button called "Submit Assessment". There i am trying to save image using ajax call and depend on the result another ajax call will be executed in order to post data to server. Coding structure as follows

JS Code:

var isPostedImage=false;
Submit Click function
{
   //call to screen lock function
   PostAssessmentData();
}

function PostAssessmentData()
{
   isPostedImage=PostImage();
   if (isPostedImage)
   {
      //AJAX call to post data to server
      async:false;
   }
}

PostImage=function()
{
  //AJAX call to save Image in server
  async:false;
  //if it is successful 
  isPostedImage=true;
}

My question is i called to lock screen function as first step. But screen does not lock until above ajax calls have been executed. I have make those async :false as well. I think deferred object is good concept to this. But i don't know how to use deferred object concept in this scenario.

Can someone please help me.

Thanks in advance


Solution

  • Freezing the screen until the chained ajax calls is complete is done like this

    What I have done:

    • showing a loader image like spinner on screen before making ajax calls.
    • The second ajax call will be executed inside the success callback of the first ajax call, so that the response received from first call is sent to second call.
    • Once all the calls are completed hide the spinner from the screen, allowing the user to interact with the screen.

    JS Code:

    $('#loading').hide();
    
    function p1() {
       return $.post("/echo/html/", {
        html: "Happy"
        });
    }
    
    function p2(firstCallData) {
        var newData = firstCallData + " Coding :)";
        return $.post("/echo/html/", {
           html: newData
        });
    }
    
    function clickHandler() {
        $('#loading').show();
        $.when(p1()).then(function (firstCallResults) {
            console.log(firstCallResults);
            $.when(p2(firstCallResults)).then(function (secondCallResults)     {
                 console.log(secondCallResults);
                 alert("All ajax calls processed.\n" + secondCallResults);
                 $('#loading').hide();
            });
        });
    }
    
    $(function () {
       $("#go").click(clickHandler);
    });
    

    Live Demo @ JSFiddle

    Note:Above solution is based on a generic idea and hence this solution should not to be considered as a final solution