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

1
  • 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. Commented Aug 23, 2010 at 15:04

4 Answers 4

20

AJAX does the magic:

$(document).ready(function(

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

));
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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>';
?>

1 Comment

what do we do if the php function is inside of a php file that contains different functions also?
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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.