Jump to content

Loading Screen appears after Submit Button is pressed


Recommended Posts

Hi folks I wanted to share a cool code with everyone when you press the Submit Button on a Form.  Well when you press the Submit Button with a file in it to load and there is a unique field in it (such as a Username for a registration form), there's a bit of a delay until you ge to the confirmation screen.  This confuses the Submitter and may press the button again - which results in an error because now the form is submitted twice but the same username was alreast submitted on the first form

Anyway you want a Loading screen to pop up.  Caspio should have this simple feature for a "low coding" platform!

In your header drop this code (#Submit is the submit button - on an update form its something different, #processing is the name of my div that will show the processing window after submission):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
  $("#Submit").click(function(){
    $("#processing").css({"display":"table"});
  });
});
</script>

In the Footer drop this:

<div id="processing"  style="display:none;background-color:rgba(222,200,70,0.9);height:100vh;width:100vw;position:fixed;top:0;"><br/><br/><span style="display:table;height:75wh;margin:auto;top:0;bottom:0;left:0;right:0;">Processing, Please Wait....<br/><br/><img style="display:table;margin:auto;" src="http://skquares.com/processing.gif"></img><br/<br/></span></div>

-------

thats it!  Notice the display is set to none because you dont want to show the window until the Submit button is pressed via the Jquery script.  Notice the height and width are set to the size of the screen with a position of fixed, top:0 - so that the whole screen is covered but you can shrink it by putting less width and height; background is my own color choice but you can change that - note leave the opacity not at 100% but I have it at 90%(0.9) so that the user can still see the form a little.  Also, http://skquares.com/processing.gif is where i store MY image so you have to change it to where you image is hosted (but you could use mine i guess).

 

Ok I hope this helps!

Link to comment
Share on other sites

  • 1 year later...

I'm curious if anyone has been able to take this logic a bit further and only display the loading screen content IF there are no errors in the form. I have tried a variation of this, but I want the user to be able to correct form errors before showing the loading screen content. I want my loading screen content to prevent any further clicking on the page, so I set it with a high z-index, and sized it to fill the window.

I went down a long rabbit hole and found this Codepen pen: https://codepen.io/sakamies/pen/yzYypW

I forked it here, and customized the code a little to match what I want to accomplish: https://codepen.io/melsenc/pen/eYWwjXX

I tried incorporating this code into my Caspio datapages, embedded in my html-based website with jQuery and Bootstrap 5 included. It seems this code is not catching the form correctly. I'm not sure if this is relevant, but most of my html pages have multiple form datapages on them. I target the correct form by querying document.forms[0] or document.forms[1], etc. This is the code I would include in a script on my html page:

var loadingSpinnerHTML = '<div id="loading-mask" class="container-fluid"><div class="row" style="height:100%;"><div id="spinner" class="col d-flex align-items-center justify-content-center"><img href="files/spinner.svg" class="img-fluid my-auto" /></div></div></div>';

var editJobForm = document.forms[0];

var newSpinner = new LoadingSpinner(editJobForm);

I have tried testing this functionality just in the Chrome browser developer console after the page has fully loaded, and it doesn't seem to have an effect, because even though the form I submit takes a few seconds to submit, my loading spinner does not become visible at all before the browser moves to the destination page.

Is there javascript functionality going on behind the scenes for my datapage that is preventing me from interfering with the form submission events?

I'd love to know if anyone has had any luck figuring this out.

Edited by melsenc
I forgot to include declaring a variable in my example
Link to comment
Share on other sites

4 hours ago, melsenc said:

I'm curious if anyone has been able to take this logic a bit further and only display the loading screen content IF there are no errors in the form. I have tried a variation of this, but I want the user to be able to correct form errors before showing the loading screen content. I want my loading screen content to prevent any further clicking on the page, so I set it with a high z-index, and sized it to fill the window.

I went down a long rabbit hole and found this Codepen pen: https://codepen.io/sakamies/pen/yzYypW

I forked it here, and customized the code a little to match what I want to accomplish: https://codepen.io/melsenc/pen/eYWwjXX

I tried incorporating this code into my Caspio datapages, embedded in my html-based website with jQuery and Bootstrap 5 included. It seems this code is not catching the form correctly. I'm not sure if this is relevant, but most of my html pages have multiple form datapages on them. I target the correct form by querying document.forms[0] or document.forms[1], etc. This is the code I would include in a script on my html page:

var editJobForm = document.forms[0];

var newSpinner = new LoadingSpinner(editJobForm);

I have tried testing this functionality just in the Chrome browser developer console after the page has fully loaded, and it doesn't seem to have an effect, because even though the form I submit takes a few seconds to submit, my loading spinner does not become visible at all before the browser moves to the destination page.

Is there javascript functionality going on behind the scenes for my datapage that is preventing me from interfering with the form submission events?

I'd love to know if anyone has had any luck figuring this out.

I believe Validation is a backend thing unless you want to validate each field using JavaScript yourself, would putting the loading screen AFTER submission not work, does the form have to be on the background?

 

image.png.829294ef72625bae19fac27211eda8c8.png

 

but, I guess it doesn't really make sense to put loading screen AFTER submission.

Link to comment
Share on other sites

16 hours ago, TellMeWhy said:

I believe Validation is a backend thing unless you want to validate each field using JavaScript yourself, would putting the loading screen AFTER submission not work, does the form have to be on the background?

 

image.png.829294ef72625bae19fac27211eda8c8.png

 

but, I guess it doesn't really make sense to put loading screen AFTER submission.

I'm willing to investigate javascript validation if it is the only way to display a loader WHILE my form is in the process of submitting. The reason I want to do this is: my form takes a long time to submit, and I want to display a visual representation of the form submitting to my users, so they know something is happening. I have already been able to cut down the submission time from roughly 12 seconds to around 5 seconds, by changing the data source for the datapage to just one table, rather than a complicated joined View. However, getting it to be less than 5 seconds is still going to be a big project for me.

Do you have any advice for writing javascript for form validation? The main thing I need to validate is I want to make sure required fields have been filled out. Thanks!

Link to comment
Share on other sites

2 hours ago, melsenc said:

I'm willing to investigate javascript validation if it is the only way to display a loader WHILE my form is in the process of submitting. The reason I want to do this is: my form takes a long time to submit, and I want to display a visual representation of the form submitting to my users, so they know something is happening. I have already been able to cut down the submission time from roughly 12 seconds to around 5 seconds, by changing the data source for the datapage to just one table, rather than a complicated joined View. However, getting it to be less than 5 seconds is still going to be a big project for me.

Do you have any advice for writing javascript for form validation? The main thing I need to validate is I want to make sure required fields have been filled out. Thanks!

Well, it's pretty much a bunch of if else, 

For example, if I have these three fields that I want filled, I can check it like this
 

<script>

document.addEventListener("BeforeFormSubmit", function tx(Ev){

var field1=document.getElementById("InsertRecordTitle").value;
var field2=document.getElementById("InsertRecordTEXT").value;
var field3=document.getElementById("InsertRecordTry_add").value;

var arr=[field1, field2, field3];


if(arr.includes("")){
Ev.preventDefault(); //from the function tx(Ev) above, prevents Form to Submit

alert("Please fill all required fields.");

}

});

</script>

 

Link to comment
Share on other sites

On 8/20/2021 at 10:49 AM, TellMeWhy said:

Well, it's pretty much a bunch of if else, 

For example, if I have these three fields that I want filled, I can check it like this
 

<script>

document.addEventListener("BeforeFormSubmit", function tx(Ev){

var field1=document.getElementById("InsertRecordTitle").value;
var field2=document.getElementById("InsertRecordTEXT").value;
var field3=document.getElementById("InsertRecordTry_add").value;

var arr=[field1, field2, field3];


if(arr.includes("")){
Ev.preventDefault(); //from the function tx(Ev) above, prevents Form to Submit

alert("Please fill all required fields.");

}

});

</script>

 

Thank you. I was able to add this at the bottom of my html page. I wanted to add that I also wrote some script for the footer of my datapage, to dynamically add the styling of Caspio's required asterisk, to add a visual clue for which fields are required:

<script>
document.addEventListener('DataPageReady'function (event) {
// Add the required form field styling, to work with the javascript validation in the parent html page
var label1 = $("label[for*='InsertRecordjobType']");
var label2 = $("label[for*='InsertRecordmachine_group']");
var label3 = $("label[for*='InsertRecordquantity']");
 
var jobDept = document.getElementsByName("InsertRecordjobType")[0].value;
 
var labels = [label1label2label3];
 
// Required fields will be hidden by the datapage Rules if they aren't required.
// (Don't require quantity if job department is ART. Only make machine_group required if the job department isn't ART, DTG, or O.)
 
// Add the required asterisk for required fields
$.each(labelsfunction (ilabel) {
 
    var originalHTML = $(label).html();
 
    originalHTML += '<span class="cbFormRequiredMarker"><span class="cbFormRequiredMarker">*</span></span>';
    
    $(label).html(originalHTML);
 
});
 
});
Link to comment
Share on other sites

Lastly, I wanted to share my solution for adding back in the spinner, now that I'm handling the Javascript validation on my own.

At the bottom of the body of my HTML page, I have this spinner div:

 
    <div id="loading-mask" class="container-fluid" style="display: none;">
        <div class="row" style="height:100%;">
            <div class="col d-flex align-items-center justify-content-center">
                <img src="files/spinner.svg" alt="spinner loading icon" class="img-fluid my-auto">
            </div>
        </div>
    </div>

and this script element:

 
    <!-- Validate the New Job form with javascript, to allow the spinner to function correctly -->
    <script>
        // (The Caspio required markers will be added from the Job New datapage footer)
 
        // Throw an alert and cancel form submission if required fields are left blank
        document.addEventListener("BeforeFormSubmit"function tx(Ev) {
 
            var field1 = document.getElementsByName("InsertRecordjobType")[0].value;
            var field2 = document.getElementsByName("InsertRecordmachine_group")[0].value;
            var field3 = document.getElementsByName("InsertRecordquantity")[0].value;
 
            var arr = [];
 
            // Don't require quantity if job department is ART. Only make machine_group required if the job department isn't ART, DTG, or O.
            if ( field1.startsWith('A') ) {
                arr = [field1];
            } else if ( field1.startsWith('D') || field1.startsWith('O') ) {
                arr = [field1field3];
            } else {
                arr = [field1field2field3];
            }
 
            if (arr.includes("")) {
                Ev.preventDefault(); //from the function tx(Ev) above, prevents Form to Submit
 
                alert("Please fill all required fields.");
 
            } else {
                navButtonSpinner();
            }
 
        });
 
    </script>

The key part of the script element is the function call of navButtonSpinner(), which I define in an external .js file thus:

 
    function toggleDisplayBlock(id) {
        var x = document.getElementById(id);
        x.style.display = "block";
    }
 
    function navButtonSpinner() {
        toggleDisplayBlock("loading-mask");
    }

 

Thanks for your help, @TellMeWhy!

Link to comment
Share on other sites

  • 8 months later...

I'm trying to do something like this, but for the Generate PDF link (the new one that came with the Templates update) instead of the Submit button.

$(document).ready(function(){
  $(".cbGenerateTemplatesLink").click(function(){
    $("#processing").css({"display":"table"});
    setTimeout(function(){
      $("#processing").css({"display":"none"});
    }, 15000)
  });
});

It is working only when the page loads up the first time. However, if the user updates anything on the page (causing a refresh of the details page) before clicking the Generate PDF link, the loading screen does not pop up. 

I've tried getting rid of the document.ready listener, leaving it with just the click event, and the same thing happens.

Any ideas?

 

*Edit, this does the same thing.

document.querySelector('[class="cbGenerateTemplatesLink"]').addEventListener("click", function(){
  document.getElementById('processing').style.display = 'table';
  setTimeout(function(){
    document.getElementById('processing').style.display = 'none';
  }, 15000)
})

 

Link to comment
Share on other sites

  • 1 year later...

Hi everyone,

I use this script which works fine for me. I hope it works for you too!

Add this HTML to your webpage:

<style type="text/css">
#loader{
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: 99999;
    background: #FFF;
}
.loader {
    border: 12px solid #f3f3f3;
    border-radius: 50%;
    border-top: 12px solid #444444;
    width: 70px;
    height: 70px;
    animation: spin 1s linear infinite;
}
.center {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
@keyframes spin {
    100% {
        transform: rotate(360deg);
    }
}
</style>

<div id="loader" style="display: none;">
	<div class="loader center"></div>
</div>

<script type="text/javascript">
	document.addEventListener('BeforeFormSubmit', function(event) {
      	//always display the loader when button is clicked
		document.querySelector('#loader').style.display = 'block';
	});

	document.addEventListener('FormSubmitted', function(event) {
      	//hide the loader when form is submitted
		document.querySelector('#loader').style.display = 'none';

      	//get the Caspio Dapatage unique element ID
		var elementID = event.detail.UniqueSuffix;
      	//datapage error element
		var errorMsg = document.querySelector("div#cbDataAjaxCtnr" + elementID + " [data-cb-name='HeaderErrorMsg']");
      	//datapage success element in case you have set to display a message after form submission
		var successMsg = document.querySelector("div.cbConfirmationMessages#PostBackMessage" + elementID);

		if(errorMsg){
          	//IF THE ERROR ELEMENT IS PRESENT
          	//do whatever here, I use a toast notification but you can use an alert or anything you want
			console.log('Error, please verify the entered data');
		}else if(!errorMsg && !successMsg){
          	//IF NO ERROR AND NO SUCCESS MESSAGE IS PRESENT (When you select SAME FORM option on datapage submission)
			console.log('Record has been saved');
		}else if(successMsg){
          	//IF THERE IS A SUCCESS MESSAGE (When you select DISPLAY A MESSAGE after submitting the datapage)
			
			if(successMsg.innerText == 'DELETED'){
              	//In the message box, you must type DELETE so it recognizes you are deleting something and you can customize the message shown to the user.
				console.log('Record was successfully deleted');
			}else if(successMsg.innerText == 'SAVED'){
              	//In the message box, you must type SAVED so it recognizes you are saving/updating something and you can customize the message shown to the user.
				console.log('Record has been saved');
			}
		}
	});
</script>

Inside a HTML block in your datapage, I recommend you to add this code to control that the loader is hidden when datapage loads:

<script type="text/javascript">
document.querySelector('#loader').style.display = 'none';
</script>

Happy coding!

Link to comment
Share on other sites

  • 4 months later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...