使用AJAX调用PHP函数

This question already has answers here:
Closed 3 years ago.

I've read all the topics about my question but cannot solve my problem. I want to get php function result using jQuery AJAX.

function fetch_select(){
  val_name = $('#name').val();
  $.ajax({
    type: 'POST',
    url: 'include/get_db.inc.php',
    data: {
           name: val_name,
    },
    success: function (response) {
      document.getElementById('higtchart_medie_gen').innerHTML=response;
      columnChart( JSON.parse(response));
    }
  });
}

function columnChart(data_v){
  if(data_v.length >0){
    $(function () {
      $('#higtchart_medie_gen').highcharts({
        chart: {
          type: 'column'
         },
......

#name is id for select tag.
My code for get_db.inc.php is:

<?php
function test_name () {
  $ret = [];
  if(isset($_POST['name'])){
    $name = $_POST['name'];
    $sql = "SELECT 
            ......
            WHERE ID = $name ";
    $result = $conn->query($sql);
    if($result->num_rows > 0){
      while($row = $result->fetch_assoc()) {
        $ret [] = [$row['NAME'] . ' ' . $row['LASTN'], floatval($row['AVGG'])];
      }
    }
  }
  if(count($ret) >1) echo json_encode($ret);
  else echo 'Not working';
}
?>

How can I call test_name function from Ajax code? Thank you very much!

</div>

You do almost correct but only one mistake is you forget to invoke the function. What you do is just send the data to this file.

So, to fixed this. Just add test_name() to your get_db.inc.php

 <?php
      function test_name () {
           $ret = [];
           if(isset($_POST['name'])){
                $name = $_POST['name'];
                $sql = "SELECT 
                 ......
                WHERE ID = $name ";
                $result = $conn->query($sql);
                if($result->num_rows > 0){
                     while($row = $result->fetch_assoc()) {
                          $ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
                     }
                }
           }
          if(count($ret) >1) echo json_encode($ret);
          else echo 'Not working';
     }

     test_name()
 ?>

Also it will be better to check isset outside the function.

function test_name ($name) {
     $ret = [];
     $sql = "SELECT 
     ......
     WHERE ID = $name ";
     $result = $conn->query($sql);
     if($result->num_rows > 0){
           while($row = $result->fetch_assoc()) {
                $ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
           }
     }
     if(count($ret) >1) echo json_encode($ret);
     else echo 'Not working';
}

if(isset($_POST['name'])){
    test_name($_POST['name'])
}

This will make your function to be pure. It will easier to debug later and it will not invoke if you don't have $_POST['name'].