Jadin Hornsby
Jadin Hornsby

Reputation: 11

Dynamically call PHP Function with ajax

I had a question; How would one call multiple PHP functions and output them onto the page?

Now i have found a way, could anyway let me know how i could improve my answer. It works perfectly, I just want to see what could be a better way.

AJAX CALL;

$.ajax({ 
    url: 'functioncalls.php', //URL TO PHP FUNCTION CONTROL
    data: {call: 'Login', parameters: {Username, Password}}, //CALL the function name with an array of parameters
    type: 'post'
}).done( function( Output ){
    try{
     Output  = JSON.parse(Output); // see if out put is json as that is what we will pass back to the ajax call
    } catch (e){
        alert('Error calling function.');
    }
});

PHP "functioncalls.php" page

if(isset($_POST['call']) && !empty($_POST['call'])){ //check if function is pasted through ajax
    print call_user_func_array($_POST['call'], $_POST['parameters']);//dynamically get function and parameters that we passed in an array
}

PHP FUNCTION - make sure your function is either on the page or included

function Login($Username, $Password){
    // function control
    return json_encode($return);// return your json encoded response in value or array as needed
}

And that's that, Nothing else needed you can call any function and use it in your done ajax promise.

Note: Your parameters have to be passed as an array.

Thank you

Upvotes: 0

Views: 479

Answers (1)

mtizziani
mtizziani

Reputation: 1016

change your ajax request like this

$.ajax({ 
    url: 'functioncalls.php', //URL TO PHP FUNCTION CONTROL
    data: {call: 'Login', parameters: JSON.stringify([Username, Password])}, //CALL the function name with an array of parameters
    type: 'post'
}).done( function( Output ){
    try{
     Output  = JSON.parse(Output); // see if out put is json as that is what we will pass back to the ajax call
    } catch (e){
        alert('Error calling function.');
    }
});

in php you have to do something like this:

$params = json_decode($_POST['parameters']);
login($params[0], $params[1]);

Upvotes: 1

Related Questions