Home > Article > Backend Development > How to call php function from js
JS method of calling php function:
jQuery.ajax({ type: "POST", url: 'your_functions_address.php', dataType: 'json', data: {functionname: 'add', arguments: [1, 2]}, success: function (obj, textstatus) { if( !('error' in obj) ) { yourVariable = obj.result; } else { console.log(obj.error); } }});
Your _function_address.php is as follows:
<?php header('Content-Type: application/json'); $aResult = array(); if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; } if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; } if( !isset($aResult['error']) ) { switch($_POST['functionname']) { case 'add': if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) { $aResult['error'] = 'Error in arguments!'; } else { $aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1])); } break; default: $aResult['error'] = 'Not found function '.$_POST['functionname'].'!'; break; } } echo json_encode($aResult);?>
Recommended: phpserver
The above is the detailed content of How to call php function from js. For more information, please follow other related articles on the PHP Chinese website!