gelviis
gelviis

Reputation: 458

Loading content in a PHP file with JQuery

I have the code below loading in the content I have in the test.php file. There's a lot of code in the php file so takes a bit of time to load. When it does load the "load content" text remains. I want to be able to: - display a loading symbol whilst the page is loading - hide the "load content" text once the content has appeared

How would I do this?

    <script type="text/javascript">
          $(document).ready(function(){
            $("a").click(function(){
            $("#test").load('test.php');
          });
       });
    </script>

<div id="test"></div>
<a>Load content</a>

UPDATE:

Also I would like the it to be a link (as it currently doesn't work on a touch device) - any suggestions?

Upvotes: 1

Views: 2150

Answers (5)

djmccormick
djmccormick

Reputation: 463

Please see the jQuery documentation for .load(). Here's how you can achieve this:

<script type="text/javascript">
    $(document).ready(function(){
        $("a").click(function(){
            // Display a loading message:
            $("#test").html('<p>Loading...</p>');

            // Load our data:
            $("#test").load('test.php', function() {
                // Code here runs when the load() completes:
                $("a").hide();
            });
        });
    }); </script>

<div id="test"></div> <a>Load content</a>

Upvotes: 1

tpow
tpow

Reputation: 7884

You need to use "print" in your PHP script.

When I do this, I use jquery ajax and show the response in the onSuccess

Upvotes: 0

Jasper
Jasper

Reputation: 76003

You could either nest the <a> tag inside the <div id="test"> tag so it is removed when the .load() function is complete or add code to hide/remove the <a> tag in the callback function for the AJAX call:

<div id="test"><a>Load content</a></div>

Or in your JavaScript

$("a").click(function(){
    /*Code to show loading message*/
    $("#test").load('test.php', function () {
        //this is a callback function that will fire after the data from test.php is loaded into the test div
        $('a').hide();//or you can use .remove() to completely remove the tag
        /*Code to remove the loading message*/
    });
});

Upvotes: 3

mattacular
mattacular

Reputation: 1889

Switch to $.ajax(). $.load and $.get are helper shortcut methods to the master .ajax() method which allows for many more configuration options.

Set your loader animation in the beforeSend callback, and remove it in the onComplete callback (this callback is run regardless of whether the pull is a success or error). You may want to do other things in the success/error callbacks accordingly.

http://api.jquery.com/jQuery.ajax/

Upvotes: 0

OptimusCrime
OptimusCrime

Reputation: 14863

Put the Load content inside the div. The load will overwrite this when it's done.

Upvotes: 1

Related Questions