0

How I can start a MySQL query only when my page is fully loaded ?

I need that because my query impact much data and increase the time of load of the page for my visitor :/

I tried with this code without success =>

<script type="text/javascript">
$(window).load(function() {
<?php
include(BASE . "sql-query.php");
?>
});
</script>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
WolwX
  • 121
  • 1
  • 15
  • I think your basic understanding of the differences between JavaScript (=client side) and PHP (=server side) needs some improvements... You should definitely have a look at AJAX: https://api.jquery.com/jQuery.ajax/ – Reeno Apr 12 '14 at 15:29
  • See also http://stackoverflow.com/a/7016795/1682509 – Reeno Apr 12 '14 at 15:30
  • possible duplicate of [Reference: Why does the PHP (or other server side) code in my Javascript not work?](http://stackoverflow.com/questions/13840429/reference-why-does-the-php-or-other-server-side-code-in-my-javascript-not-wor) – Quentin Apr 12 '14 at 15:31

3 Answers3

1

This won't work like you expect.

PHP is serverside and HTML/Javascript is clientside. That means that all PHP is loaded and executed by the time JavaScript gets to do their work.

You should read about ajax. This is a JavaScript feature that fetches information/data from other resources. You could load the entire page, show a "Loading"-symbol, execute the ajax-request and wait for the response.

jQuery.ajax is a nice place to start.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
1

Assuming the file where there's the query is sql-query.php, use that code (ps: remember to include jquery library!):

[into <head>]
<script type="text/javascript">
$(window).load(function() {
$("#query").load("sql-query.php");
});
</script>
[into <body>]
<div id="query">Loading...</div>
  • Thanks :D I used your tips and that's ok, that's really optimised the time of load of my page, and the MySQL queries still working fine :) – WolwX Apr 12 '14 at 20:18
0

Assuming sql-query.php returns something, try this:

$.(document).ready(function() {
   $.ajax({
       url: 'sql-query.php',
       success: function (data) {
           // Manipulate data here
       }
   });
});
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47