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
-
i think your problem is that post doesn't work with multidimensional inputs. just simple key value pairs. I had this problem too.mtizziani– mtizziani2017年03月16日 08:17:42 +00:00Commented Mar 16, 2017 at 8:17
-
2You are reinventing RPC/SOAP. Why not thinking about REST for decoupling frontend and backend ?n00dl3– n00dl32017年03月16日 08:17:44 +00:00Commented Mar 16, 2017 at 8:17
-
@mtizziani what would be the reasoning behind multidimensional inputs, you could pass them through to php and refactor them there?Jadin Hornsby– Jadin Hornsby2017年03月16日 08:31:35 +00:00Commented Mar 16, 2017 at 8:31
-
@n00dl3 This just seems easier, I don't completely understand nor have a iused RCP/SOAP before, but I will look into it. thank youJadin Hornsby– Jadin Hornsby2017年03月16日 08:34:19 +00:00Commented Mar 16, 2017 at 8:34
1 Answer 1
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]);
2 Comments
Explore related questions
See similar questions with these tags.