7

For me this is something new, so I am just researching this and trying to understand it. As you can see in the php script there are 2 functions and I am trying to call a specific one with jquery.

Now if I have one function then I can do it, but when I have 2 or more I am starting to get stuck. I suppose I could do this when I have 2 functions, but as soon as more variables are in play or more functions do I just make massive if statements in my php?

The problem is that when I attach a database to it, I would need to consider all inputs that can happen. How do I specify a specific php function when using jquery & ajax?

//function.php
<?php
    function firstFunction($name)
    {
        echo "Hello - this is the first function";
    }

    function secondFunction($name)
    {
        echo "Now I am calling the second function";
    }

?>

<?php
    $var = $_POST['name'];

    if(isset($var))
    {       
        $getData = firstFunction($var);
    }
    else if(isset($var))
    {
        $getData = secondFunction($var);
    }
    else
    {
        echo "No Result";
    }

?>

//index.html
<div id="calling">This text is going to change></div>

<script>

     $(document).ready(function() {
        $('#calling').load(function() {
        $.ajax({
            cache: false,
            type: "POST",
            url: "function.php",
            data: 'name=myname'
            success: function(msg)
            {
                $('#calling').html((msg));
            }

            }); // Ajax Call
        }); //event handler
    }); //document.ready

</script>
3
  • sidenote: In the else case of isset($var), you're passing a null to your secondFunction() Commented Sep 5, 2014 at 1:26
  • Yeah, but what if there is an if else? Then how would it know what statement to go to? Commented Sep 5, 2014 at 1:27
  • the ajax is a red hearing, its irreverent Commented Sep 5, 2014 at 1:29

3 Answers 3

12

You need to pass a parameter in, either via the data object or via a GET variable on the URL. Either:

url: "function.php?action=functionname"

or:

data: {
    name: 'myname',
    action: 'functionname'
}

Then in PHP, you can access that attribute and handle it:

if(isset($_POST['action']) && function_exists($_POST['action'])) {
    $action = $_POST['action'];
    $var = isset($_POST['name']) ? $_POST['name'] : null;
    $getData = $action($var);
    // do whatever with the result
}

Note: a better idea for security reasons would be to whitelist the available functions that can be called, e.g.:

switch($action) {
    case 'functionOne':
    case 'functionTwo':
    case 'thirdOKFunction':
        break;
    default:
        die('Access denied for this function!');
}

Implementation example:

// PHP:
function foo($arg1) {
    return $arg1 . '123';
}

// ...
echo $action($var);

// jQuery:
data: {
    name: 'bar',
    action: 'foo'
},
success: function(res) {
    console.log(res); // bar123
}
Sign up to request clarification or add additional context in comments.

3 Comments

IMO, don't use function_exists() on $_POST values. Potential security error / have chance to corrupt the page / server. Imagine the action is fopen , passthru or ini_set...
So is action: a keyword for the function name?
@JeffKranenburg yes, it's just an example variable name. As Raptor mentioned, calling any function may not be appropriate - so I'd suggest a whitelist instead (will add to answer)
4

You are actually quite close to what you want to achieve.

If you want to specify which function will be called in PHP, you can pass a variable to tell PHP. For example, you passed request=save in AJAX, you can write the PHP as follow:

$request = '';
switch(trim($_POST['request'])) {
  case 'save':
    $player_name = (isset($_POST['playername']) ? trim($_POST['player_name']) : 'No Name'));
    saveFunction($player_name);
    break;
  case 'load':
    loadFunction();
    break;
  default:
    // unknown / missing request
}

EDIT: You can even pass along with other parameters

1 Comment

Ah I see what you are saying, cool I will have a play with that.
0

This may not be exactly what you are looking for but it can help some others looking for a very simple solution.

In your jquery declare a variable and send it

var count_id = "count";

data:
{
    count_id: count_id
},

Then in your php check if this variable is set

if(isset($_POST['count_id'])) {

Your function here

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.