Now that my woes with running the big .sql file within PHP (Using a PHP session variable within a MySQL file run in PHP) are dealt with I want to display a loading bar (.gif) that I've made and a message displaying that the user data is being uploaded into the database because I don't want the user to think that their browser is not loading the page (since this process can take up to a couple of minutes depending on the file size).
<img src='includes/loadingbar.gif' width='128' height='15' alt=''/></p>
Uploading your school data into the database, please wait.
This process can take a while depending on your file size and connection.
Above is the image and the message I want to display while the query is running, but I can't seem to get past the white loading screen while it is updating the data. I've tried echo'ing the message after the query, before the query, as HTML code placed before and after the PHP command - but all I get is still this evil white screen. Every time the loading message doesn't show up until the query has finished (ironically), is there a way for it to show during the query in the format I'm currently using, or do I have to steer towards other programming languages? Many thanks!
EDIT:
I've tried to use a command before and after the php tags but it still doesn't operate until after the query has finished:
<div id="message" div align="center"><img src="includes/loadingbar.gif" width="128"
height="15" alt=""/>
<br />
Please wait while your school data is being uploaded into the database.
This can take a short while depending on your file size and connection.
</div>
<script type="text/javascript">
$(document).ready(function()
{$('message').show(); });
</script>
<?php
session_start();
$page_title = 'SQLTest';
include ('includes/header.html');
require ('mldb_connect.php');
(etc...)
and at the end:
if ($populateresult)
{
$replace = $_SESSION['path'].$_SESSION['CentreNo'].'_'.$_SESSION['School'].'_'
.date('dmY_His').'.txt' ;
rename ($path, $replace) ;
}
?>
<script type="text/javascript">
$(window).load(function()
{$('message').hide();});
</script>
What am I doing wrong with this?
With jQuery you could do something like this:
$("#imgId").show(); // Show loading image.
Execute PHP script:
$.post( "your_script.php", function( data ) {
// $("#imgId").hide(); // Hide loading image.
window.location = "http://www.example.com"; // Redirect to URL.
});
Update: imgId being the id of your image. For instance:
<img src="image.png" id="imgId" />
I can tell you two different solutions.
Sol 1. When the query is firing as the page is loading: (with out Ajax):
In this case you can use some jquery.
$(document).ready(function(){
$('img').show();
});
$(window).load(function(){
$('img').hide();
});
This will ensure that when all the elements of the page are loaded only when the loader image hides.
sol 2.
if you want to do it via Ajax. Show the image when the event is fired that triggers Ajax, then upon the .success() or the .done() of the Ajax hide the image loader.
Though this is an old question, but it can be done without javascript.
need 'sessions_start()'.
forward to a page with please wait dialog and in the head section forwarder <meta http-equiv="refresh" content="1; url= http://example.com/myPage.php"
Related
I'm trying to make a little and simple chat system on PhP.
My Idea was simple really, I have a form that send a text to a script in PHP and that script save the var in a Database, then the other user refresh the page to download the new message and display it on the chat box.
The problem comes, when I say refresh the page.
I just think that probably would be a problem for the user refresh the entire page every second or less thank's to a JavaScript function.
The original idea was to use setInterval() but know I'm thinking that this can be a bad idea.
I'm not sure, but from chrome when you refresh a form it will save the form and fill it automatically, once you have finished the refresh, does every browser do that?
Willa a JavaScript function for refreshing the page be a problem for who have a really slow connection?
But most important, to fix the problem, is actually possible to just refresh a specific PHP script, that allow the user to refresh only that script and download the new message, without refreshing the entire page every second?
All the help would be appreciated.
-NOTE-
To be honest, the guy that want me to do that chat system asked me to not use JavaScript, so theoretically I'm not even allowed to use setInterval()
For refreshing part you can use <META http-equiv="refresh" content="3; URL=truc.php"> instead of setInterval (by the way, setTimeout is enough as it will occurs 1 time at each page refresh).
For the form refilling, when you submit the message it will refresh the page and free the form so it's ok. For the guy who just "read", if he started to type something and the page refresh it should keep it after refresh so il looks ok too ? But you can add autocomplete="off" to make sure form won't suggest anything undesired.
Use the jQuery function called load(). Post a basic HTML markup of your chat page and I will edit with a specific answer.
$("#messageboard").load("chat.php #messageboard > *");
Put this code after the submit of the chat inside your ajax request to save. Change #messageboardfor the ID of the message board div that needs to be refreshed. Change chat.php for the page where the chat is displayed. In order to save loading time, you can pass on GET vars to the chat page and prevent a full load of the page and return only the messages.
You can also have the setTimeout function but both needs to run on the page so the user submitting the message sees a refresh right away (no lag)
function startTimer() {
$("#messageboard").load("chat.php #messageboard > *", function(){
//repeats itself after 1 seconds
setTimeout(startTimer, 1000);
});
}
startTimer();
In the above, 1000 is in milliseconds so equal to 1 seconds.
Using setTimeout has the advantage that if the connection hangs for some time you will not get tons of pending requests since a new one will only be sent after the previous one finished.
I am assuming you are using ajax to submit the user message so the page does not refresh every time a user posts something. Need an example for that?
<html>
<head>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script>
$('document').ready(function(){
$('#submit').click(function(){
var message = $('#message').val();
$('#message').reset();
$.post('chat.php',{message: message},function(response){
$("#messageboard").load("chat.php #messageboard > *");
});
})
$('#message').keypress(function(e){
if(e.which == 13){//Enter key pressed
var message = $('#message').val();
$('#message').reset();
$.post('chat.php',{message: message},function(response){
$("#messageboard").load("chat.php #messageboard > *");
});
}
});
function startTimer() {
$("#messageboard").load("chat.php #messageboard > *", function(){
//repeats itself after 1 seconds
setTimeout(startTimer, 1000);
});
}
startTimer();
});
</script>
</head>
<body>
<div id="messageboard"></div>
<input type="text" placeholder="Message" id="message"><input value="submit" type="button" id="submit">
</body>
</html>
The above will trigger a POST on the submit button but also if the user hits enter. The script will auto refresh but also refresh on a new input submit. This is just a concept. Make sure you create the server side handler to save the messages to DB.
You could use php cache to avoid refreshing the page and handle messages in a file located on the server if you just want to use php, which is server side.
You can check for some file content in a while loop, and display then erase it until timeout for exemple. A submit form could write the data to the file using php. You can make XML if you want, but here is a raw way to do it :
The file displaying / flushing data in your browser :
testChat.php
<?php
$timeout=200;
set_time_limit($timeout+1);//Maximum execution time.
flushBrowser();//Print space chars to have cache flush on browsers.
$str='';
while ($timeout>0){
//Flush data to display
ob_flush();
flush();
if ($str!=checkPostMsgQueued())
echo checkPostMsgQueued()."\n";
$str=checkPostMsgQueued();
//wait...
sleep(1);
$timeout-=1;
}
ob_end_flush();
//Many browsers seems to receive some data before flushing.
function flushBrowser(){
if (ob_get_level() == 0) ob_start();
echo str_pad('',4096)."\n";
}
function checkPostMsgQueued(){
$filename="testChat.txt";
if (file_exists($filename)){
$stream=fopen($filename, 'r');
$str=stream_get_line($stream,128);
fclose($stream);
}
return $str;
}
testchatsubmit.php :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="testChatSubmit.php" method="post">
<input type="text" name="message" id="message">
<input type="submit" name="submit">
</form>
</body>
</html>
<?php
if (isset($_POST['message'])){
$fp = fopen('testChat.txt', 'w');
fwrite($fp, $_POST['message']);
fclose($fp);
}
?>
BTW, as i said, maybe it's a bit harsh to do it this way...
I think you have no option but using some client side langage to display and post data on the same page :)
Good luck !
Edit :
Here is way to to it :
Make another html file, with 2 iframes :
testchatframes.html :
<iframe src="testchat.php"></iframe>
<iframe src="testchatsubmit.php"></iframe>
I also modified some chunks of the initial testChat.php code to make it work on multiple "clients" (I tried on localhost), using streams instead of brutally deleting lines... I don't think this is the right way to do (maybe you should notice "the guy who want you to do that" ) this but that is quite fun and working ! It does not even seem to be so ressource expensive... :) Cheers !
I retrieve about 15,000 rows from my database every time I visit this page.
The page might take about 8-10 seconds to finish load everything - I currently, use DataTable.
I think it would be nice to show user any kind of loading feedback during that time.
I want to create my own loading animations, and chose my own color, style, and size.
I'm not if I use any Ajax call.
I am just retrieving a lot of data out of my database.
What is the most efficient way to show loading animation while retrieving data from database ?
To begin with, the most simple solution is to use ajax call to retrieve the table rows populated by php.
JSFiddle
SIMPLE:
main.html / main.php
/*This makes the timeout variable global so all functions can access it.*/
var timeout;
/*This is an example function and can be disregarded
This function sets the loading div to a given string.*/
function loaded() {
$('#loading').html('The Ajax Call Data');
}
function startLoad() {
/*This is the loading gif, It will popup as soon as startLoad is called*/
$('#loading').html('<img src="http://rpg.drivethrustuff.com/shared_images/ajax-loader.gif"/>');
/*
This is an example of the ajax get method,
You would retrieve the html then use the results
to populate the container.
$.get('example.php', function (results) {
$('#loading').html(results);
});
*/
/*This is an example and can be disregarded
The clearTimeout makes sure you don't overload the timeout variable
with multiple timout sessions.*/
clearTimeout(timeout);
/*Set timeout delays a given function for given milliseconds*/
timeout = setTimeout(loaded, 1500);
}
/*This binds a click event to the refresh button*/
$('#start_call').click(startLoad);
/*This starts the load on page load, so you don't have to click the button*/
startLoad();
img {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='start_call'>Refresh</button>
<div id='loading'></div>
An example of the php would look something like this
example.php
/*Database call to get list*/
foreach($list as $li){
echo "<tr><td>$li[var1]</td><td>$li[var2]</td></tr>";
}
ADVANCED:
A more advanced way to load your content is to use webworkers and multiple database calls segregated into small chunks.
You would set up web-workers to do small 100 row results and use LIMIT in your sql statements to page the results into small chunks. Then you can page through the first 100 results while the other results are loading.
This process is more difficult and takes longer to implement, but leads to seamless and quick loading.
EDIT:
If you want to change the loading animation just change the URL. and if you want the URL to be loaded on page load put it in the div itself.
/*This will make the img load on page load rather than DOM execution.*/
<div id='loading'>
<img src="http://rpg.drivethrustuff.com/shared_images/ajax-loader.gif"/>
</div>
The Image doesn't have to be an image. It can be any loading icon you want. A gif was quick and dirty. You could use something like font-awesome spinner
data.php to check out the DB and build the table's HTML
function getData(){
//div contains the loader
$('#loader').show();
$.get('clients/data.php', function(data) {
//
$('#content').html(data);
//hide the loader
$('#loader').hide();
//build DataTable
$('#content table').dataTable();
});
}
getData();
This depends on what language you use, but the fundamentals are the same. You load the page with just the animation while the query completes, and then replace the animation with the content.
In jQuery this probably means linking the animation in plain HTML, then separately calling the database with AJAX. When you get the result, you can use jQuery append to target the content area, and write into that in real time.
I include PHP since you say that you are not using AJAX, but in PHP the structure is the same: You would need to link the image, flush the page so that it displays, and then execute your query. Cover the animation with negative CSS margin-top on the search results, and Bob is your uncle.
Your question :
"I want to create my own loading animations, and chose my own color, style, and size."
You should visit http://www.ajaxload.info/ there you can chose,customize and download loading gif really fast.
I have recently installed Simple Mailing List 2 (currently in beta) and I have got everything to work so far. The main thing that was left for me to do was to make a custom php page which the signup form redirects to once submitted. The content that the page shows is based on what the user enters in the email field and returns one of three results:
an error message if the email syntax is incorrect.
a custom message if the user has subscribed telling them to check their email.
a custom message if the user has chosen to unsubscribe.
That's the background out of the way. Now what I intend to do is show a popup window that includes the contents of the redirected php page (ie. one of the three results) instead of going to a new page. Is it possible to do this a css popup box so I don't have to open up a new window?
Thankyou
Adam
You can use JavaScript to send an ajax request to the PHP page that will do the calculations, the result will then be sent to your "window" content and then you show the window to the user
You're mixing metaphors. CSS is just a presentational technology that you use to determine the style of something. There is no such thing as a "css popup box".
What you want to do is have an HTML element (likely a div) that contains the information you intend to show, initially set to not be visible (you use CSS for this with the display:none; style). What you're describing is essentially an AJAX interaction that uses Javascript to parse the contents of the form, send data to the server to be evaluated, and return a message to be displayed (without triggering a postback/going to a new page). That Javascript would also handle the CSS part of setting the display of the HTML element to true.
This is a fairly common scenario, so you should be able to find snippets online.
...but here's a super dumb example
<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<form action="#">
<input type="text" id="enterStuff" />
</form>
<div id="response" style="display:none;">
<p id="message">Put stuff in me</p>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
registerEventListeners();
});
function registerEventListeners(){
jQuery("#enterStuff").change(getData);
}
function getData(){
jQuery.ajax({
type : 'POST',
data : {
stuff : jQuery("#enterStuff").val(),
},
url : "http://localhost/myprocessor.php",
success : showCool,
complete : updateDisplay
});
}
function showCool(data, textStatus, jqXHR){
var selector = jQuery("#message");
selector.val(data)
}
function updateDisplay() {
jQuery("#response").show();
}
</script>
</body>
</html>
Then your myProcessor.php would have to read the value of the variable, do some logic, and echo a response.
You could use an <iframe> as an in-document 'pop-up', you just set the target of the form to the name/id of the iframe. (You can use some JavaScript to only show the iframe once the form is submitted.)
okay so on my home page i'm doing a user name and password check and then im using jquery document.location to send you to a logged in page say secure.php.... while this works it sends you to secure.php first and then images start loading ... how can i do it in such a way that it loads the entire page and then send you to secure.php
example : -
$.ajax ({
url: loginCheck.php,
type: 'POST',
data: username + password ,
success: function (check){
if(check==1)
document.location= /loginpage/secure.php
else alert(invalid username or pass)
}
});
Edit: I'm replacing my entire question now that I understand what you are trying to do. In secure.php, put all of your code in a containing div, something like this:
<body>
<div id="contentContainer">
<!-- content goes here -->
</div>
</body>
Set a style for #contentContainer to be hidden:
#contentContainer {
display: none;
}
Add a window.onload handler to show the div. Unlike onready, onload isn't called until all of the content has loaded including images.
$(window).load(function() {
$("#contentContainer").show();
});
You may want to do the same thing in reverse to a "loading" div with a message that says "loading...". Ie, initially display it, and hide it in the onload handler.
Edit: You can speed up the loading of the page by pre-loading the images in a hidden div in the previous page.
Home.php
<div class="preloader">
<img src="..." />
...
</div>
.preloader {
display: none;
}
Secure.php should load using the cached images.
...this strikes me as highly unsecure, but oh well.
Unless you build a metaframework in jQuery where all page loads are performed in a "shell" and then displayed only when ready to render, the answer is, I'm pretty sure, you can't.
Pages have a definite life cycle. jQuery and AJAX kinda blur the line a bit, but a page load is a singular event that controls the scripts. Loading the page would make the script you were using to load the page go away.
How can I load individual Div separately without affecting current page and show loading status for that div with PHP and MySQL or Ajax and SQL
I do this:
first you have the hidden div with a loading if in it and a load button:
<div id="displayDiv" style="display: none">
<img id="loadingGif" src="loadingGif" style="display:none"; />
<div id="actualContent" style="display:none" />
</div>
<input type="button" id="loadButton" />
Then you have the JS code ( I use jQuery )
<script type="text/javascript">
$(document).ready( onDocumentReady); // this runs before page load
function onDocumentReady()
{
$('#loadButton').click( onLoadClick ); //assign action on button click
}
function onLoadClick()
{
$('#loadingGif').show(); // show the loading gif. It won't show as long as it's parent is hidden
$('#actualContent').hide(); // hide the actual content of the response;
$('#displayDiv').show(); // display the div
$.get("test.php", onRequestComplete ); // make the ajax request to the stand alone PHP file
//so as long as the content loads, the loading gif will show;
}
function onRequestComplete( data )
{
$('#loadingGif').hide();
$('#actualContent').html( data );
$('#actualContent').show();
}
</script>
So. You have a container "displayDiv"; inside you have an image "loadingGIf" and another container "actualContent"; When you click the load button, the big container with the loading gif appears, notifying the user that something is loading. When the content is loaded, you just hide the loadingGif, and display the info in the "actualContent" gif. In the test.php you just echo what must appear in the div. I recommend using JSON, but you'll read more about it.
Hope this helps.
Use PHP+AJAX + Mysql create a ".php" file containing that , call the Ajax function in which this .php(DO not give this name t your file, this is just an reference example) file must be called.. which will displayed as per the event call...