Contact Form

Name

Email *

Message *

Cari Blog Ini

Ajax Get Data From Database Javascript

How to Get Data from a Database Using Ajax

Introduction

Ajax (Asynchronous JavaScript and XML) is a technique for creating interactive web applications that can update content without reloading the entire page. This can make your website more responsive and user-friendly. In this tutorial, we will show you how to get data from a database using Ajax using simple Javascript (no jQuery).

AJAX and PHP: A Simple Example

We will be using a PHP file called getcustomer.php to handle the Ajax request. The PHP file will run a query to fetch the data from the database and return the results in JSON format. Here is the code for the getcustomer.php file: ```php query($sql); // Convert the result to JSON format $json = json_encode($result->fetch_assoc()); // Return the JSON response echo $json; ?> ``` Now, let's create the JavaScript function to make the Ajax request: ```javascript function GetEmployeeUsingAjax(EmpId) { // Create an XMLHttpRequest object var xhr = new XMLHttpRequest(); // Open the request xhr.open('GET', 'getcustomer.php?customerID=' + EmpId, true); // Set the response type to JSON xhr.responseType = 'json'; // Send the request xhr.send(); // Handle the response xhr.onload = function() { if (xhr.status == 200) { // The request was successful console.log(xhr.response); } else { // The request failed console.log('Error: ' + xhr.status); } }; } ``` To use the Ajax function, you can call it with the customer ID as the argument. For example: ```javascript GetEmployeeUsingAjax(2); ``` This will make an Ajax request to the getcustomer.php file, fetching the data for the customer with the ID of 2. The response will be logged to the console.


Comments