Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
 $stmt->execute();
 $stmt->close();
like image 447
Lmxc Avatar asked Sep 21 '13 00:09

Lmxc


2 Answers

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.

CSS

#loading_spinner { display:none; }

HTML

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

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

jQuery

$('#loading_spinner').show();

var post_data = "my_variable="+my_variable;
$.ajax({
    url: 'ajax/my_php_page.php',
    type: 'POST',
    data: post_data,
    dataType: 'html',
    success: function(data) {
        $('.my_update_panel').html(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
        $('#loading_spinner').hide();
    },
    error: function() {
        alert("Something went wrong!");
    }
});

PHP (my_php_page.php)

<?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
?>
like image 195
TheCarver Avatar answered Oct 04 '22 18:10

TheCarver


You can't really do this in PHP itself, you'd have to do something in JavaScript for that. So what you would probably want to do is have JQuery show a loading spinner, then execute an AJAX request to your PHP job, and when you get data back, hide the loading indicator.

like image 32
mszaro Avatar answered Oct 04 '22 20:10

mszaro