简体   繁体   中英

How to call a php function in javascript using Ajax?

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM