RETRIEVE RECORDS FROM A DATABASE THRU API IN JAVASCRIPT

 Code:

index.js



document.addEventListener("DOMContentLoaded", ()=>{
  displayStudents();
});

const displayStudents = async() =>{
  //GET
  const baseApiUrl = "http://localhost/jslecture/api";

  const response = await axios.get(`${baseApiUrl}/students.php`,{
    params:{operation:"getAllStudents"}
  });
 
  if(response.status == 200){
    displayStudentsTable(response.data);
  }else{
    alert("Error!");
  }
}

const displayStudentsTable = (students) =>{
  const mainDiv = document.getElementById("main-div");

  const table = document.createElement("table");

  const thead = document.createElement("thead");
  thead.innerHTML = `
      <tr>  
        <th>ID</th>
        <th>LAST NAME</th>
        <th>FIRST NAME</th>
        <th>COURSE</th>
        <th>ADDRESS</th>
      </tr>
    `;
  table.appendChild(thead);

  const tbody = document.createElement("tbody");
  students.forEach(student => {
    let row = document.createElement("tr");
    row.innerHTML = `
        <td>${student.stud_school_id}</td>
        <td>${student.stud_last_name}</td>
        <td>${student.stud_first_name}</td>
        <td>${student.crs_code}</td>
        <td>${student.stud_address}</td>
      `;
    tbody.appendChild(row);
  });
  table.appendChild(tbody);

  mainDiv.appendChild(table);
}




 students.php

<?php
  header('Content-Type: application/json');
  header("Access-Control-Allow-Origin: *");

  class Student {
    function login($json){
      include "connection-pdo.php";
   }

    function getAllStudents(){
      //connect to the database
      include "connection-pdo.php";

      $sql = "SELECT a.*, b.crs_code
              FROM tblstudents a INNER JOIN tblcourses b
              ON a.stud_course_id = b.crs_id
              ORDER BY a.stud_last_name";
      $stmt = $conn->prepare($sql);
      $stmt->execute();
      $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);

      echo json_encode($rs);
    }
  }

  //submitted by the client - operation and json
  if ($_SERVER['REQUEST_METHOD'] == 'GET'){
    $operation = $_GET['operation'];
    $json = isset($_GET['json']) ? $_GET['json'] : "";
  }else if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $operation = $_POST['operation'];
    $json = isset($_POST['json']) ? $_POST['json'] : "";
  }

  $student = new Student();
  switch($operation){
    case "getAllStudents":
      echo $student->getAllStudents();
      break;
    }

?>

 connection-pdo.php

<?php
    $servername = "localhost";
    $dbusername = "root";
    $dbpassword = "";
    $dbname = "dbschool";

    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //echo "Connected successfully";
    } catch(PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
?>

 

 index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>JS Modules</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script type="module" src="./js/index.js"></script>
  </head>
  <body>
    <div id="header-div"><h1 id="header-text">STUDENTS DATABASE</h1></div>
    <div id="main-div">
    </div>
    <div id="footer-div"></div>
  </body>
</html>

 

 

 

 

 

No comments:

Post a Comment

INSERT RECORDS TO MYSQL DATABASE THRU PHP API FROM JAVASCRIPT

 students.php <?php   header ( 'Content-Type: application/json' );   header ( "Access-Control-Allow-Origin: *" );   cla...