TransWikia.com

How to call a php function in javascript using Ajax?

Stack Overflow Asked by MR Skan on December 14, 2020

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.

2 Answers

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)

Correct answer by bluejayke on December 14, 2020

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.

Answered by Amadan on December 14, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP