Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

First and foremost thank you for checking out my problem, and for any help you may give!

Okay, so like the title says I'm in need of calling a php function from my index page, which adds a new record in my database as a vote, using JQuery Ajax. This function will return one integer, which will then be printed inside the form button in which it was called from.

Anyone have an idea on how I would accomplish this? Any guidance is appreciated!

Edit:

So if I'm using a template object I can just call the
function using ajax and it will return the output? 
What would I use as the URL? index.php?  

Such as...
function DoVote() {
    $.ajax({
    type:'POST',
    url: 'index.php',
    success: function(data) {
    $('#voteText').html(data);
 }
});

And the form action attribute is posted I'm guessing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
334 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes, create a separate PHP file that calls that function and echos the output. Then load that php file with an AJAX request.

Because PHP is a server side language and jQuery (JavaScript) is Client side you can't directly call a PHP function with it, the most you can do is load a file. However, if the file has something like <?php echo($object->function()); ?> you can load the file, in essence calling the function.

I'm not sure that (your addition) is correct.

In an arbitrary file you have a PHP function:

<?php
    // Called "otherfile.php"

    // Function you're trying to call
    function doSomething($obj)
    {
        $ret = $obj + 5;

        return($ret);
    }
?>

And you have a file (call it ajaxcall.php) that you will load with that AJAX call.

<?php
    include("otherfile.php");   // Make the file available, be aware that if that file 
                                // outputs anything (i.e. not wrapped in a function) it
                                // may be executed
    // Grab the POST data from the AJAX request
    $obj = $_POST['obj']; 

    echo($doSomething());
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...