Stay Tuned!

Subscribe to our newsletter to get our newest articles instantly!

Javascript

How to fetch data from database in Javascript using AJAX

Fetching data from a database dynamically enhances web applications’ capabilities. AJAX (Asynchronous JavaScript and XML) allows seamless data retrieval from a server without reloading the entire webpage. Let’s explore how to fetch data from a database using AJAX in JavaScript.

Setting Up

1. Create a Server-Side Script

Set up a server-side script (e.g., PHP, Node.js, Python) to handle database requests and return data in JSON format. For example, using PHP:

<?php
// Establish database connection

// Fetch data from the database (e.g., using PDO)
// Example query: SELECT * FROM your_table_name

// Encode data as JSON
echo json_encode($result);
?>

2. HTML Structure

Create an HTML structure to display fetched data:

<div id="data-container"></div>

JavaScript Logic

1. Fetch Data Using AJAX

Write JavaScript code to fetch data from the server using AJAX (here, using the XMLHttpRequest object):

function fetchData() {
  const xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      const data = JSON.parse(this.responseText);
      displayData(data);
    }
  };

  xhr.open('GET', 'your_server_script.php', true);
  xhr.send();
}
  • XMLHttpRequest handles asynchronous requests to the server.
  • onreadystatechange listens for changes in the request status.
  • JSON.parse() converts the received JSON response into a JavaScript object.

2. Display Fetched Data

Create a function to display the fetched data:

function displayData(data) {
  const dataContainer = document.getElementById('data-container');
  data.forEach(item => {
    const element = document.createElement('p');
    element.textContent = `${item.id}: ${item.name}`; // Customize based on your data
    dataContainer.appendChild(element);
  });
}
  • forEach iterates through the fetched data and creates elements to display it in the designated container.

3. Call the Function

Invoke the fetchData function to initiate the data fetching process:

fetchData();

Testing the Functionality

Ensure that the server-side script is correctly set up to retrieve data from the database and return it in JSON format. Replace 'your_server_script.php' with the correct path to your server-side script.

Conclusion

Fetching data from a database using AJAX in JavaScript enables dynamic and asynchronous data retrieval, enhancing the responsiveness and interactivity of web applications. Utilize this technique to seamlessly integrate data from databases into your web projects, providing users with real-time information without page reloads.

Avatar

Carolina

About Author

Leave a comment

Your email address will not be published. Required fields are marked *

You may also like

Javascript Tech

How to change Lowercase to Uppercase in Javascript

There are many variations of passages of Lorem Ipsum available but the majority have suffered alteration in that some injected
Javascript

How to refresh page after update in JavaScript

In JavaScript, refreshing a page after an update is a common requirement to ensure users view the latest content or
en_USEnglish