Search code examples
phpmysqlloadingdie

Show a loading symbol whilst running a PHP script


I have created a Sign Up page on my website, where users enter their details and click a button which then does some word checks, send an email, inserts the information into a MySQL database and finally ends with a die() statement.

The only problem is that this process can take up to 30 seconds depending on the internet speed of the client. This means that the Sign Up page is displayed for a long period of time which would make a less tech-savvy user (and even a very tech-savvy user!) think the page is broken, which would cause them to close down the website and never come back!

So I need a solution and I think the easiest way to keep a User on the site is to display a loading symbol to say that it's working and how long left. Even though there is a URL loading symbol in the browser tab, it is slow moving and not many people do see it at all.

Basically I am asking for a way to display the loading symbols whilst the script runs and then goes away once it reaches the die() statement. I don't mind which language it's written in but would prefer PHP.

Thanks in advance


Solution

  • The most simple method to achieve this would be to use some JavaScript to attach an event listener to the submit event of your form, then display some message / loading icon / something from that event listener method.

    A quick example (but there are many-many other approaches):

    ...
    <form ... onsubmit="showLoadingMessage();" ...>
    ...
    
    <script>
    function showLoadingMessage() {
      var message = document.createElement('div');
      message.innerHTML = 'We are working. Please wait...';
      document.body.appendChild(message);
    }
    </script>
    

    Of course, you can display anything else instead of that simple text message and you can append to or position that message div where you want to.