2

I have a file called myfunctions.php where I have a lot of functions, like

function sendForm(){
    //save form
}
function fn2(){
 //do something
}
 // Other functions ...

and the jquery code,

$.ajax({
    url: "myfunctions.php",
    type: "POST",
    contentType: "application/x-www-form-urlencoded",
    data: {key1: "value1", key2: "value2", key3: "value3"},
    complete: function(){
        //completado
        alert("complete");
    }
});

I need call specific function in this file; for example sendForm(). How can I do that?

2 Answers 2

3

In PHP

<?php
// create a list of approved function calls
$approved_functions = array('sendForm','fn2');

// check the $_GET['function'] and see if it matches an approved function
if(in_array($_GET['function'], $approved_functions))
{
    // call the approved function
    $_GET['function']();
}

function sendForm(){
    //save form
}
function fn2(){
 //do something
}

In AJAX

// specify which function to call
url: "myfunctions.php?function=sendForm",
Sign up to request clarification or add additional context in comments.

2 Comments

But I going to do this for more the 50 function... Other suggestion?
No, I recommend no other approach. If you are willing to give up the security and integrity of your web application then you can just skip the $approved_functions checking and execute whatever $_GET['function'] has inside of it. Just call $_GET['function'](); but just know that you will be subject to unwanted function injection like this url: "myfunctions.php?function=phpinfo",
1
$.ajax({
    //...
    data: {key1: "value1", key2: "value2", key3: "value3", type:0},
    //...
});

myfunctions.php:

<?php
//...
if (!isset($_POST['type'])) { /* return something */ exit; }
$type = $_POST['type'];
if ($type == 0)
{
    function1();
} else if ($type == 1) {
    function2();
} //etc.
//...
?>

2 Comments

Aren't there another way?
@omixam No, this is the safest and most standard way.

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.