ahfreak
ahfreak

Reputation: 119

How to add a loading screen when doing a AJAX call in Phonegap?

Title pretty much says it. How do I add a loading screen when AJAX is running and make the loading screen disappear when it AJAX has finished running?

My AJAX function:

$("#loginBtn").on("click", function(e){
e.preventDefault();

var loginForm = document.getElementById("loginForm");
var login_data = $('#loginForm').serialize();

  $.ajax({
    type: "POST",
    url: serverURL + "loginProcess.php",
    data: login_data,
    dataType:"json",
    success: function(data){
      localStorage.setItem('id', JSON.stringify(data));
    },
    error:  function(jqXHR, textStatus, errorThrown) {
      navigator.notification.alert('Invalid Email or Password!',null,'Error', 'Done');  
    }
  }); 

});

Note: I'm not using jQuery Mobile.

Upvotes: 2

Views: 12637

Answers (4)

jcesarmobile
jcesarmobile

Reputation: 53301

To globally show a loading page on every ajax call you can use this code:

$( document ).ajaxStart(function() {
    $( "#loading" ).show();
});

and hide it when the ajax calls stop

$( document ).ajaxStop(function() {
    $( "#loading" ).hide();
});

you need a full screen div with the id loading, and a loading image gif or something like that

Upvotes: 6

AtanuCSE
AtanuCSE

Reputation: 8940

Don't forget to use async:true and use $.mobile.loading("show"); for loader showing

jQuery.ajax({
                url: serverURL + "loginProcess.php", 
                global: true,
                type: "POST",
                data: login_data,
                dataType:"json",
                async: true,
                timeout: 40000,
                beforeSend: function() {
                     $.mobile.loading("show");
                },
                complete: function(){
                     $.mobile.loading("hide");
                },
                success: loading_complete_list,

        });

Upvotes: 1

Shoeb Ansari
Shoeb Ansari

Reputation: 27

$("#loginBtn").on("click", function(e){
e.preventDefault();

var loginForm = document.getElementById("loginForm");
var login_data = $('#loginForm').serialize();

  $.ajax({
    type: "POST",
    url: serverURL + "loginProcess.php",
    data: login_data,
    dataType:"json",
    beforeSend:function(){
    blockUI(); //Call block function
    },
    success: function(data){
      localStorage.setItem('id', JSON.stringify(data));
    },
    error:  function(jqXHR, textStatus, errorThrown) {
      navigator.notification.alert('Invalid Email or Password!',null,'Error', 'Done');  
    }
  }); 

Upvotes: 0

Shoeb Ansari
Shoeb Ansari

Reputation: 27

You can use jQuery BlockUI Plugin

Your code would be

var blockUI = function(){
    $.blockUI({ 
        fadeIn: 1000, 
        timeout:   0,
        message:'<h1>Loading...</h1>',
        //css: { border: '5px solid red'},
        onBlock: function() {
            $("#tab3").addClass("myClass");
        }
    });
}

Upvotes: 0

Related Questions