Search code examples
phpjsongetjson

Defining a specific function for .getJSON


I am trying to use Json to get data from a database by calling the function.php to query the database. I am running into an issue with finding out how I specify a specific function in the function.php file to do the work.

Below is my Jquery and function.php the goal is to have Json use getlist() from function.php.

Please help I have been trying to understand this for some time now.

Jquery Function:

$.getJSON( "public/includes/functions.php", function( data ) {
        var items = [];
      $.each( data, function( key, val ) {
        console.log('data:' + key + ' And ' + val);
      });

     });

PHP Function:

function getlist(){

    require "dbconn.php";
    $result = $stdb->get_results("SELECT id, name FROM supplements");
    $stdb->show_errors();


    if (mysqli_num_rows($result) > 0) {
    // output data of each row
        while($row = mysqli_fetch_assoc($result)) {

         $array[] = $row;

        }
    } else {
        echo "0 results";
    }
    $js_array = json_encode($array);
    echo $js_array;

    mysqli_close($conn);    
}

Solution

  • $.getJSON( "public/includes/functions.php?myfun=1", function( data ) {
            var items = [];
          $.each( data, function( key, val ) {
            console.log('data:' + key + ' And ' + val);
          });
    
         });
    
    
    
        <?php 
        if(isset($_GET)){
            if(isset($_GET['myfun'])){
            getlist();exit;
    }
        }
        function getlist(){
    
            require "dbconn.php";
            $result = $stdb->get_results("SELECT id, name FROM supplements");
            $stdb->show_errors();
    
    
            if (mysqli_num_rows($result) > 0) {
            // output data of each row
                while($row = mysqli_fetch_assoc($result)) {
    
                 $array[] = $row;
    
                }
            } else {
                echo "0 results";
            }
            $js_array = json_encode($array);
            echo $js_array;
    
            mysqli_close($conn);    
        }
        ?>