简体   繁体   中英

javascript- show loader in ajax call & hide after success

I'm a little bit confused here.

I am creating a form in javascript and posting the values to a php page ( submit.php ) and if the php page returns success, I will redirect the user to another page success.php

var url = 'submit.php';
var furl = 'success.php';
var formdata = new FormData();
formdata.append("name", 'John');
formdata.append('staffid',123);
formdata.append('csrf_test_name',csrf_token);

var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function(event) {
    uploadcomplete(event,furl);
}, false);
ajax.open("POST", url);
ajax.send(formdata);

function uploadcomplete(event,furl) {
    var response = event.target.responseText.trim();
    if(response=='Failed') {
        alert('Failed');
    } else {
        alert('Success');
        window.location.replace(furl);
    }
}

function showLoader(){
    document.getElementById('loader').style.display = 'block';
}

function hideLoader(){
    document.getElementById('loader').style.display = 'none';
}

Thing is, I wanna show a loader icon when the form data is getting process and hide it when it's complete. For that, I created two functions showLoader() and hideLoader()

My question is, where should I include these functions?

You do it like so:

While the request is in progress :

ajax.addEventListener("progress", showLoader);

When loading done :

ajax.addEventListener("load", hideLoader);

You can use it with readyState with onreadystatechange event:

var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
  if(ajax.readyState === 0){ 
    showLoader(); 
  }else if(ajax.readyState === 4){
    hideLoader();
  }
};

Or within your code you can call them here:

var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function(event) {
    uploadcomplete(event,furl);
    hideLoader(); //<------------------hide the loader here when done.
}, false);
ajax.open("POST", url);
showLoader(); // <------------------call and show loader here.
ajax.send(formdata);

With Plain JS, you can do it like this:

function loadData() {
    var ajax = new XMLHttpRequest();

    ajax.onreadystatechange = function() {
        if (ajax.readyState === 4 ) {
           if (ajax.status === 200) {
               hideLoader();
               //your code after ajax response, use ajax.responseText
           }
           else {
               console.log('Some error...');
           }
        }
    };

    ajax.open("POST", url);
    ajax.send(formdata);
    showLoader();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM