Skip to content

Instantly share code, notes, and snippets.

@timbergus
Last active November 24, 2022 08:41
Show Gist options
  • Select an option

  • Save timbergus/4714227 to your computer and use it in GitHub Desktop.

Select an option

Save timbergus/4714227 to your computer and use it in GitHub Desktop.
Working with AJAX (jQuery and Javascript) and functions in PHP. This helps to reduce the number of files we usually need, to execute PHP functions from AJAX. With this we don't need one PHP file per function.
/* Javascript jQuery AJAX functions file */
function functionName(functionName, functionParameters)
{
$.ajax({
type: 'POST',
url: 'ourFunctionsFile.php',
async: false,
data:
{
functionName: functionName,
functionParameters: functionParameters
},
success: function(data)
{
// Do whatever you want with the returned data
}
});
}
/* PHP functions file */
/* You have to choose the appropiate function name and parameters
and pass them as an array to be read by the choosen function. */
$functionName = $_POST['functionName'];
$functionParameters = $_POST['functionParameters'];
switch ($functionName)
{
case 'firstCaseFunction':
firstCaseFunction(functionParameters);
break;
case 'secondCaseFunction':
secondCaseFunction(functionParameters);
break;
case '...':
...(functionParameters);
break;
default:
echo 'No function selected';
break;
}
function firstCaseFunction(functionParameters)
{
echo 'This is the first case function output.';
}
function secondCaseFunction(functionParameters)
{
echo 'This is the second case function output.';
}
function ...(functionParameters)
{
echo '...';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment