MomasVII
MomasVII

Reputation: 5081

Load div last after page load

Ok So I have a div that loads some data and makes the entire page load slowly. Fortunately this data can wait and I would like to load it last. I've seen the other posts like this but need a bit more help getting it to work as I am fairly inexperienced.

So for example I have:

<div id="stuff">
<?php Some PHP Here ?>
</div>

Now I have

$(window).load(function () {
    $('#stuff').load('');
});

A few questions...Do I create an empty div and then fill it with the data or can I have the data in there and then specify that to load last, which would be preferred if possible.

I understand I can have a webpage loaded like $('#stuff').load('stuff.php'); but I use a variable inside the div so how would I pass it to that load function and into the php page?

I just don't know how to pass variables up to the javascript everytime that div is loaded as it's in a while loop.

Thanks for the help.

Upvotes: 1

Views: 5168

Answers (1)

Dejv
Dejv

Reputation: 954

Because javascript processes on client side and PHP runs on server side, you cannot do PHP operations on HTML that have already been loaded (page has already been sent from server to client, so it is not reachable by PHP anymore).

Bacause of this fact you are going to need javascript AJAX for this.

Because you are beginner I suggest you use an ajax function from jQuery javascript framework for this matter. It works the same as javascript function and handles many operations automatically.

As you correctly presumed, you can first display your empty div and then, ... after page is fully loaded, you can call your ajax.

This ajax basically asks PHP script to provide loaded page with data that will be displayed in specified html element.

Code should look like this:

Include this to your PHP file with content that you load:

<script type="text/javascript">http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js</script> <!--loads jquery framework-->

<script type="text/javascript">  
  $(document).ready(function() {
    //when page is loaded
    $.ajax({
      url: "ajax.php" //script with your data selection
    }).done(function(data) { //when ajax call success
      $("#ajax-element").html(data); //insert data returned from ajax.php into div with id ajax-element
    });
  });
</script>


<div id="ajax-element"></div>

This is PHP ajax file that will return data for you (just echo everything that you want to have in your "ajax-element" div, for example:

<?php
 echo "some text";
?>

For more info you can find jquery AJAX specification here.

Upvotes: 3

Related Questions