Reputation: 89
I am new to javascript and ajax, I want to call php function which returns the patient age in a javascript file so I tried to explore the answers I found here concerning this question but I couldn't resolve it, here is the php file called get-patient-age.php:
function getPatientbyId($id) {
$q = DB::pdo()->prepare("SELECT p.birthday FROM patient AS p WHERE id_patient = :patient");
$q->bindValue(':patient', (int)$id , PDO::PARAM_INT);
$q->execute();
return $q->fetch(2);
}
And here is how I tried to call it using ajax:
$.ajax({
type: "GET",
url: 'get-patient-age.php',
dataType: 'json',
data: {functionname: 'getPatientbyId', arguments: 1},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
;
console.log(obj.result);
} else {
console.log(obj.error);
}
}
});
I am getting 200 ok as a response but always empty, am I missing anything? Any advice could help, thanks.
Upvotes: 0
Views: 296
Reputation: 1
You can't get the functions of php with JavaScript, you can only read back the return value the server gives you
On the server side you need to listen for get requests, and if it contains "functionname" then call the function and send the return value to the page
So in the PHP file
var isFunc = $_GET["functionname"]
var args = $_GET["arguments"]
if(isFunc== "getPatientbyId") echo getPatientbyId(args)
Upvotes: 1
Reputation: 198496
An AJAX request to your web server executes a PHP file, not a PHP function. Your PHP file defines the function getPatientbyId
and does not execute it. Your PHP code needs to also invoke the function, output a Content-Type
header saying that there is JSON in the response, format the result of the function as JSON, and print it.
Upvotes: 1