Mastering AJAX: Fetching Data with JavaScript Fetch API

Efficient data exchange is a crucial aspect of developing dynamic applications, achievable both with and without AJAX.

JavaScript offers XMLHttpRequest for initiating AJAX requests, but its implementation can be tricky and challenging to recall.

In JavaScript, there is another method fetch() which simplifies the process of sending AJAX requests and is more user-friendly when compared to XMLHttpRequest.

In this tutorial, I show how you can use Fetch API to send GET and POST request using JavaScript and PHP.

Mastering AJAX: Fetching Data with JavaScript Fetch API


Table of Content

  1. Create a Table and insert records
  2. Create a Database Configuration file
  3. HTML – User Interface Setup
  4. PHP – Handle AJAX request
  5. JavaScript – Send GET and POST requests using Fetch API
  6. Output
  7. Conclusion

1. Create a Table and insert records

Create employees table and insert some data.

CREATE TABLE `employees` (
   `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
   `emp_name` varchar(80) NOT NULL,
   `city` varchar(80) NOT NULL,
   `email` varchar(80) NOT NULL
);

INSERT INTO `employees` (`id`, `emp_name`, `city`, `email`) VALUES
(1, 'Yogesh', 'Bhopal', 'yogesh@makitweb.com'),
(2, 'Vishal', 'Pune', 'vishal@makitweb.com'),
(3, 'Vijay', 'Jaipur', 'vijayec@makitweb.com'),
(4, 'Rahul', 'Kanpur', 'rahul512@makitweb.com'),
(5, 'Sonarika', 'Mumbai', 'bsonarika@makitweb.com'),
(6, 'Jitentendre', 'Bhopal', 'jiten94@makitweb.com'),
(7, 'Aditya', 'Pune', 'aditya@makitweb.com'),
(8, 'Anil', 'Indore', 'anilsingh@makitweb.com'),
(9, 'Sunil', 'Nagpur', 'sunil1993@makitweb.com'),
(10, 'Akilesh', 'Surat', 'akileshsahu@makitweb.com');

2. Create a Database Configuration file

Create a config.php file for database configuration.

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = "root"; /* Password */
$dbname = "tutorial"; /* Database name */

// Create connection
$con = new mysqli($host, $user, $password, $dbname);

// Check connection
if ($con->connect_error) {
   die("Connection failed: " . $con->connect_error);
}

3. HTML – User Interface Setup

Create a textbox to enter employee id for and a button to fetch record according to the entered id in the textbox for this defined onclick event which calls fetchuserdetails() function.

In addition to the individual record fetching, create another button specifically for retrieving all employee records. To do this, define an onclick event that calls the fetchAll() function when this button is clicked.

To display the fetched data in an organized manner, generate an HTML table with the following ID: <table id="employeesTable">. This table will be used to list and present the employee records effectively.

<input type="text" id="txt_empid" value="0"> &nbsp; <button id="btn_fetchdetails" onclick="fetchuserdetails();">Fetch a user</button> <br><br>
<button id="btn_fetchall" onclick="fetchAll();">Fetch all users</button><br><br>

<!-- List records -->
<table id="employeesTable" border="1" style="border-collapse: collapse;">
    <thead>
        <tr>
            <td>ID</td>
            <td>Name</td>
            <td>Email</td>
            <td>City</td>
        </tr>
    </thead>
    <tbody></tbody>
</table>

4. PHP – Handle AJAX request

Create ajaxfile.php file to handle AJAX requests. From here, handle 2 requests –

Fetching All Records

If $request == "fetchallrecords" then retrieve all records from the employees table. Loop through the fetched records, creating a new <tr> element for each record. The HTML for these rows will be stored in the $html variable. Finally, the $html content will be stored within a response array and returned in JSON format.

Fetching a Record by ID

If $request == "fetchrecordbyid" then read POST empid and assign it to $empid variable. Fetch a record from the employees table where the ID matches $empid. Create a new <tr> element, store the HTML in the $html variable, and include it in the response array. Return $response Array in JSON format.

<?php 

include "config.php";

$request = "";
if(isset($_GET['request'])){
     $request = $_GET['request'];
}

// Fetch all records
if($request == 'fetchallrecords'){

     // Fetch records
     $sql = "select * from employees";
     $records = mysqli_query($con, $sql);

     $html = "";
     if(mysqli_num_rows($records) > 0){

          while($row = mysqli_fetch_array($records)){

               $html .= "<tr>";
               $html .= "<td>".$row['id']."</td>";
               $html .= "<td>".$row['emp_name']."</td>";
               $html .= "<td>".$row['email']."</td>";
               $html .= "<td>".$row['city']."</td>";
               $html .= "</tr>";

          }

     }else{

          $html = "<tr>
               <td colspan='4'>No record found.</td>
          </tr>";

     }

     // Return response
     $response = array(
          'status' => 1,
          'data' => $html
     );

     echo json_encode($response);
     die;

}

// Fetch a record by ID
if($request == 'fetchrecordbyid'){

     // POST data
     $postdata = json_decode(file_get_contents("php://input"));

     $empid = $postdata->empid;

     // Fetch record
     $sql = "select * from employees where id=".$empid;
     $records = mysqli_query($con, $sql);

     $html = "";
     if(mysqli_num_rows($records) > 0){

          $row = mysqli_fetch_array($records);

          $html = "<tr>";
          $html .= "<td>".$row['id']."</td>";
          $html .= "<td>".$row['emp_name']."</td>";
          $html .= "<td>".$row['email']."</td>";
          $html .= "<td>".$row['city']."</td>";
          $html .= "</tr>";

     }else{

          $html = "<tr>
               <td colspan='4'>No record found.</td>
          </tr>";

     }

     // Return response
     $response = array(
          'status' => 1,
          'data' => $html
     );

     echo json_encode($response);
     die;

}

5. JavaScript – Send GET and POST requests using Fetch API

In JavaScript, we will create two functions:

1. fetchUserDetails(): This function is designed to load a specific record by its ID. It operates as follows:

  • Read the value from the textbox and assign it to the empid variable.
  • Check if empid is greater than 0.
  • If empid is greater than 0, set up a POST request with the following options:
    • Create a data variable and store {empid: empid} in it.
    • Define the method, headers, and include the data in the request body as body: JSON.stringify(data).
  • Send a fetch() request to "ajaxfile.php?request=fetchrecordbyid".
  • On a successful callback, append data.data to the <tbody> element.

2. fetchAll(): This function is designed to load all records. It operates as follows:

  • Send a fetch() request to "ajaxfile.php?request=fetchallrecords".
  • Upon a successful callback, append data.data to the <tbody> element in the HTML.
// Fetch all record using Fetch API POST request
function fetchuserdetails(){

     const empid = Number(document.getElementById('txt_empid').value);

     if(empid > 0){

          // POST data
          const data = {
               empid: empid
          };

          const options = {
               method: 'POST',
               headers: {
                   'Content-Type': 'application/json', 
               },
               body: JSON.stringify(data) // Convert the data to a JSON string
          };

          // Send request
          fetch('ajaxfile.php?request=fetchrecordbyid', options)
          .then(response => {
                if (!response.ok) {
                     throw new Error('Network response was not ok');
                }
                return response.json();
          })
          .then(data => {

                // Append data to <tbody >
                const emptable = document.getElementById('employeesTable').querySelector('tbody');
                emptable.innerHTML = data.data;

          })
          .catch(error => {
                // Handle errors here
                console.error('error:', error);
          });

     }

}

// Fetch all record using Fetch API GET request
function fetchAll(){

     // Send request
     fetch('ajaxfile.php?request=fetchallrecords')
     .then(response => {
           if (!response.ok) {
                throw new Error('Network response was not ok');
           }
           return response.json(); // Parse the response as JSON
     })
     .then(data => {

           // Append data to <tbody >
           const emptable = document.getElementById('employeesTable').querySelector('tbody');
           emptable.innerHTML = data.data;

     })
     .catch(error => {
           // Handle errors here
           console.error('error:', error);
     });

}

6. Output

View Output


7. Conclusion

The Fetch API is typically viewed as a more contemporary and user-centric approach, often the top pick for modern web development. Nonetheless, if your goals include accommodating older browser versions or catering to specific demands, XMLHttpRequest could remain a feasible alternative.

If you found this tutorial helpful then don't forget to share.

Leave a Comment