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);
  return $q->fetch(2);

And here is how I tried to call it using ajax:

  type: "GET",
  url: 'get-patient-age.php',
  dataType: 'json',
  data: {functionname: 'getPatientbyId', arguments: 1},
  success: function (obj, textstatus) {
             if( !('error' in obj) ) {
             } else {

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!

Related Questions

How to determine the number of negation words per sentence

2  Asked on January 3, 2021 by user14289862


Scala getClass.getResource() returning null

4  Asked on January 3, 2021 by tower


Use background image instead of border

1  Asked on January 2, 2021 by user3808307


Appended messages collides with previous data

1  Asked on January 2, 2021 by nancy-mooree


My gRPC-Test Project just work on localhost

1  Asked on January 2, 2021 by blindmeis


URL constructor appends ‘/’ at the end of the url

0  Asked on January 2, 2021 by ayusch-jain


Using the AWS EC2 Query API

1  Asked on January 2, 2021 by xliff


guidata not updating in MATLAB GUI

3  Asked on January 2, 2021 by matias-andina


Change long click delay

7  Asked on January 1, 2021 by fhucho


Dynamic parameters startWith Rxjs

1  Asked on January 1, 2021 by luden


Passing variables from a HTML form to PHP

2  Asked on January 1, 2021 by jim-r


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir