• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / Archives for Ajax

Ajax

Receive data from JSON file with Ajax

View Demo
document.getElementById('button1').addEventListener('click', loadCustomer);
document.getElementById('button2').addEventListener('click', loadCustomers);

// Load Single Customer
// Create a function named LoadCustomer and passing the Event Object 
function loadCustomer(e){
    const xhr = new XMLHttpRequest();

    xhr.open('GET', 'customer.json', true);

    xhr.onreadystatechange = function(){

        if(this.readyState === 4 && this.status === 200){

            const customer = JSON.parse(this.responseText);

            const output = `
                <ul>
                    <li>ID: ${customer.id}</li>
                    <li>Name: ${customer.name}</li>
                    <li>Company: ${customer.company}</li>
                    <li>Phone: ${customer.phone}</li>
                </ul>
            `;

            document.getElementById('customer').innerHTML = output;
        }
    }

    xhr.send();

    e.preventDefault();
}

// Load Customers
function loadCustomers(e){
    const xhr = new XMLHttpRequest();

    xhr.open('GET', 'customers.json', true);

    xhr.onreadystatechange = function(){

        if(this.readyState === 4 && this.status === 200){

            const customers = JSON.parse(this.responseText);

            let output = '';

            // We can't just output the data, we need to loop through

            customers.forEach(function(customer)  {

                output += `
                <ul>
                    <li>ID: ${customer.id}</li>
                    <li>Name: ${customer.name}</li>
                    <li>Company: ${customer.company}</li>
                    <li>Phone: ${customer.phone}</li>
                </ul>
            `;  
            });

            document.getElementById('customers').innerHTML = output;
        }
    }

    xhr.send();

    e.preventDefault();
}

Filed Under: JavaScript Tagged With: Ajax

AJAX request from MySQL database

GitHub

HTML

PHP

JavaScript

Filed Under: JavaScript Tagged With: Ajax, PHP, SQL

AJAX – Submit data with POST request into a MySQL database

GitHub

To make it work you will need to create a database in phpMyAdmin.

HTML

PHP

JS

Filed Under: JavaScript Tagged With: Ajax, PHP, SQL

AJAX request – JSON local file

Request single JSON data

Demo
GitHub

Request array JSON data

Demo
GitHub

Filed Under: JavaScript Tagged With: Ajax, json

AJAX request – TXT file

With Ajax You can receive data asynchronously without page reload.

Method 1 – onload function

GitHub

Method 2 – readystate function

Write text from TXT file in a specific div with AJAX

Demo
GitHub

Filed Under: JavaScript Tagged With: Ajax

Primary Sidebar

  • angular.io
© 2026 WP Flames - All Right Reserved