skip to Main Content

I’m trying to make a loading screen for my webapp. I’m using PHP backend and calling a DB query. The fact is, that I expect it to take up to 5 seconds (which is fine). But I’d like to show a loading screen in the meantime and I’ve found myself somehow struggling with it.

I 100% knew this wouldn’t work, but just for illustration of what I need to achieve, I tried this:

<div id='loading'>i am loading</div>
<?php
$result = $db->query("some sql here");
if ($result)
    echo "<script>document.getElementById('loading').style.display = 'none';</script>";
?>

Although this piece of code is obviously wrong, I hope it is clear from it what I need. NOTE: I cannot really afford redirecting to another page for the loading screen (I saw this as one of the options), unless it is the only possible solution like this. Is there another way of doing this?

2

Answers


  1. I think you can use these codes:

    <div id="loading">EXAMPLE LOADING DIV </div>
    <script type="text/javascript">
        $('#loading').show();    // here loading showing
        $(document).ready(function () {
            $.ajax({
                url: 'URL ACTION',
                type: 'POST',
                dataType: 'json',
                data: { },
                success: function (data) {
                },
                error: function (error) {
                },
                complete: function() {
                    $('#loading').hide();   // here loading hide when complete query
                }
            });
        });
    </script>
    

    But this method your request with AJAX. You can open your loading div first of all. And you request query in another URL and you can post/get (http methods) URL and when query ended AJAX completed and then you can hide your loading div.

    Edit: i removed ajax request when press button code.
    $("#button").click(function () { AJAX CODE HERE });

    Login or Signup to reply.
  2. You can use an XMLHttpRequest(), I won’t be writing the HTML for this answer.

    <script>
    const xhttp = new XMLHttpRequest();
    
    xhttp.open('POST', 'url_here', true)
    xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            if (this.responseText == 'success') {
                //JS Logic For Removing Loading Screen Here
            } else if (this.responseText == 'failed') {
                //Error Handling Here
            }
        }
    }
    
    xhttp.send('data='+JSON.stringify(data_here));
    

    Then in PHP

    $data = $_POST['data'];
    $data = json_decode($data);
    
    **DB LOGIC HERE*
    
    if ($result) {
        echo 'success'
    } else {
        echo 'failed'
    }
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search