20

I have a PHP function on my site which takes a couple of seconds to complete. This holds the whole page up which I don't want.

Would it be possible with jquery to call this PHP function after the page has loaded and display the results in a div? Also to display an ajax loader image until the PHP function has completed?

I've been looking at jQuery.post but can't seem to get it to work.

Would someone be able to help?

Thank you

Brigante
  • 1,921
  • 6
  • 23
  • 33
  • 1
    It is possible using AJAX but you should probably post some of your code to give us a better idea of exactly what you're trying to achieve. – Darragh Enright Aug 23 '10 at 15:04

4 Answers4

20

AJAX does the magic:

$(document).ready(function(

    $.ajax({ url: 'script.php?argument=value&foo=bar' });

));
Otar
  • 2,561
  • 1
  • 20
  • 24
15

Thanks all. I took bits of each of your solutions and made my own.

The final working solution is:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: '<?php bloginfo('template_url'); ?>/functions/twitter.php',
            data: "tweets=<?php echo $ct_tweets; ?>&account=<?php echo $ct_twitter; ?>",
            success: function(data) {
                $('#twitter-loader').remove();
                $('#twitter-container').html(data);
            }
        });
   });
</script>
Brigante
  • 1,921
  • 6
  • 23
  • 33
10

Yes, this is definitely possible. You'll need to have the php function in a separate php file. Here's an example using $.post:

$.post( 
    'yourphpscript.php', // location of your php script
    { name: "bob", user_id: 1234 }, // any data you want to send to the script
    function( data ){  // a function to deal with the returned information

        $( 'body ').append( data );

    });

And then, in your php script, just echo the html you want. This is a simple example, but a good place to get started:

<?php
    echo '<div id="test">Hello, World!</div>';
?>
hookedonwinter
  • 12,436
  • 19
  • 61
  • 74
4

This is exactly what ajax is for. See here:

http://api.jquery.com/load/

Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.

$('#result').load('ajax/test.php');

Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).

Palantir
  • 23,820
  • 10
  • 76
  • 86