Call PHP function from jQuery?

119,037

Solution 1

AJAX does the magic:

$(document).ready(function(

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

));

Solution 2

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>

Solution 3

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

Solution 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).

Share:
119,037
Brigante
Author by

Brigante

Updated on July 29, 2022

Comments

  • Brigante
    Brigante almost 2 years

    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

  • WantIt
    WantIt almost 9 years
    what do we do if the php function is inside of a php file that contains different functions also?