简体   繁体   English

提交 HTML 表单后,在 PHP 处理期间显示加载程序

[英]Show loader during PHP processing after an HTML form submission

I have an HTML form like the one shown below, which after submitting is processed by PHP:我有一个如下所示的 HTML 表单,提交后由 PHP 处理:

<form action="<?php print $_SERVER['PHP_SELF'] ?>" method="POST" enctype="multipart/form-data" id="decisions_form">

    <!-- ... -->

    <div style="text-align:center;">
        <input type="submit" name="submit" value="Submit Decisions" id="decisions_button">
    </div>

</form>

PHP does some processing, which could take a few seconds. PHP 会进行一些处理,这可能需要几秒钟。 After processing is complete, I refresh the page as below (probably not best practice, I don't know):处理完成后,我刷新页面如下(可能不是最佳实践,我不知道):

<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // PHP...
    }
    echo ('<meta http-equiv="refresh" content="0.1;">');
?>

I would like to show a full-screen "loader/spinner", which would be activated after submitting and during PHP processing.我想显示一个全屏“加载器/微调器”,它将在提交后和 PHP 处理期间激活。 Normally, If I understand it correctly, this loader/spinner should be interrupted by the refresh page command -- which is what I want通常,如果我理解正确,这个加载器/微调器应该被刷新页面命令中断——这就是我想要的

Looking for such loaders was unsuccessful, if not totally confusing for a inexperienced person like me.寻找这样的装载机是不成功的,如果不是像我这样没有经验的人完全困惑的话。

It would be ideal if I could avoid JS and do it in a pure HTML/CSS fashion (is it even possible?).如果我能避免使用 JS 并以纯 HTML/CSS 的方式来做,那将是理想的(甚至可能吗?)。

I am not aware of a mechanism to do it in pure HTML.我不知道在纯 HTML 中执行此操作的机制。 There are probably other and more sophisticated ways to do it than what I show below, but this worked well for me.可能还有其他更复杂的方法来做到这一点,而不是我在下面展示的方法,但这对我来说效果很好。 Every time you place a call to the server, the ajax start function executes and delays 1 second (change the delay however you want) and then displays the waiting gif.每次调用服务器时,ajax start 函数都会执行并延迟 1 秒(根据需要更改延迟),然后显示等待的 gif。 When the ajaxStop function is called upon completion of the server call and stops the wait gif and enables the buttons.在服务器调用完成后调用 ajaxStop 函数并停止等待 gif 并启用按钮。 Note this should be the first tag in your html file after the css definitions.请注意,这应该是 html 文件中 css 定义之后的第一个标签。

Javascript code Javascript代码

<script defer>

$( document ).ready(function() {

    // gif on 1 second timer delay before displaying, so user does not have it appear to quickly if the delay is short.
    var loadingTimer;
    $(document).ajaxStart(function() {
        $(':button').prop('disabled', true); // disable all the buttons
        loadingTimer = setTimeout("$('#process-wait').show()", 1000); // show the waiting gif
    });
    $(document).ajaxStop(function() {
        clearTimeout(loadingTimer);
        $("#process-wait").hide(); // hide the waiting gif
        $(':button').prop('disabled', false); // enable all the buttons
    });
});

</script>

Here is the css you need to go along with that.这是您需要使用的 css。 You can make it as big as you want, by adjusting the height and width values.通过调整高度和宽度值,您可以将其设置为任意大。 Pick your own gif image simply set the url parameter to the directory path and name of the gif file.选择您自己的 gif 图像只需将 url 参数设置为 gif 文件的目录路径和名称。

#process-wait {
background: transparent url(images/process-wait.gif);
background-repeat: no-repeat;
height: 150px;
width: 150px;
z-index: 99999;
display:none;
position: absolute;
top: 50%;
left: 50%;
margin-left: 10px;
margin-top: 0px;
transform: translate(-50%, -50%);

Here's a complete example:这是一个完整的例子:

<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        header("Content-Type: application/json");
        echo json_encode($_SERVER);
        exit;
    }
?>
<!doctype html>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
<div hidden class="spinner-border text-primary" role="status">
  <span class="sr-only">Loading...</span>
</div>
<form action="<?php print $_SERVER['PHP_SELF'] ?>" method="POST" enctype="multipart/form-data" id="decisions_form">

    <input type="text" name="dummy" value="dummy value">
    <!-- ... -->

    <div style="text-align:center;">
        <input type="submit" name="submit" value="Submit Decisions" id="decisions_button">
    </div>

</form>
<div class="complete" hidden>
  Submission received<br>
  <button class="reset">Reset</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
<script>
  window.addEventListener('load', () => {
    const decisionsForm = document.querySelector('#decisions_form');
    const spinner = document.querySelector('.spinner-border');
    const complete = document.querySelector('.complete');
    const resetButton = document.querySelector('.reset');

    // Show spinner, hide form
    function formSending() {
      spinner.removeAttribute('hidden');
      decisionsForm.style.display = 'none';
    }

    // Hide spinner, show complete message
    function formSent() {
      complete.removeAttribute("hidden");
      spinner.setAttribute("hidden", true);
    }

    // Show form, hide everything else
    function reset() {
      decisionsForm.style.display = 'block';
      spinner.setAttribute("hidden", true);
      complete.setAttribute("hidden", true);
    }

    // Send form data in the background
    async function submitDecisionsForm(event) {
      // Display spinner
      formSending();

      // Collect data to send
      // event.target = the form
      // event.target.action the action property on <form action="">
      // the POST body gets set by reading the data from the form object (event.target)
      const response = await fetch(event.target.action, {method: "POST", body: new FormData(event.target)});

      // Submit is complete.. show the complete message and reset button
      formSent();

      // Format the response if you want to use it later
      const responseJson = await response.json(); // or response.text() depending on what send back from the server

      // Output to browser's dev console for debugging
      console.log(text);
    }

    // Capture submit event
    decisionsForm.addEventListener("submit", (event) => {
      // Stop form from submitting immediately by default
      event.preventDefault();

      // Send form data in the background
      submitDecisionsForm(event);
    });

    // demo: reset the form when clicking the reset button
    resetButton.addEventListener('click', reset);
  });
</script>

See comments in the code for explanation of parts.有关部分的说明,请参阅代码中的注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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