Lmxc Lmxc - 1 year ago 113
SQL Question

Show loading image while PHP is executing

I would like to show loading image while the php script is executing. I have read different answers on how to do that but most of them stated that I should have a separate php page. However I am using single page to show the rows, so how can I be able to show loading image?

Example of select query, I am using to fetch the data:

$stmt = $mydb->prepare("select * from table where firstname = ? and id = ? ");
$stmt->bind_param('ss', $firstname, $id);

Answer Source

In the majority of cases, you would have two pages. The first page, client-side, makes a call to another page, server-side, and shows a pretty spinning thing while it waits. When the server-side page finishes loading (when your query completes) your first page receives a response and then you can hide the pretty spinning thing to let your user know it's finished.

You can use AJAX - in pure Javascript or a lot simpler in jQuery - to dynamically load some data from your PHP page and show a spinning thingy while it waits. I've used jQuery here.


#loading_spinner { display:none; }


<img id="loading_spinner" src="loading-spinner.gif">

<div class="my_update_panel"></div>



var post_data = "my_variable="+my_variable;
    url: 'ajax/my_php_page.php',
    type: 'POST',
    data: post_data,
    dataType: 'html',
    success: function(data) {
//Moved the hide event so it waits to run until the prior event completes
//It hide the spinner immediately, without waiting, until I moved it here
    error: function() {
        alert("Something went wrong!");

PHP (my_php_page.php)

// if this page was not called by AJAX, die
if (!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') die('Invalid request');

// get variable sent from client-side page
$my_variable = isset($_POST['my_variable']) ? strip_tags($_POST['my_variable']) :null;

//run some queries, printing some kind of result
$SQL = "SELECT * FROM myTable";
// echo results