Reputation: 1981
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
Upvotes: 20
Views: 130161
Reputation: 2591
AJAX does the magic:
$(document).ready(function(
$.ajax({ url: 'script.php?argument=value&foo=bar' });
));
Upvotes: 20
Reputation: 1981
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>
Upvotes: 15
Reputation: 12666
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>';
?>
Upvotes: 10
Reputation: 24182
This is exactly what ajax is for. See here:
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).
Upvotes: 4