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

10,706

Solution 1

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

Solution 2

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,

        });
Share:
10,706
ahfreak
Author by

ahfreak

Currently a student and will always be a student.

Updated on June 28, 2022

Comments

  • ahfreak
    ahfreak almost 2 years

    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.

  • Kay
    Kay over 5 years
    Was this tested on IE?
  • jcesarmobile
    jcesarmobile over 5 years
    Not by me as it his a cordova question, so I only tested in cordova, but ask jquery team, it should work there too