• Skip to main content
  • Skip to primary sidebar

Web Development Archive

  • Archive
You are here: Home / JavaScript / Receive data from JSON file with 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

About Gabor Flamich

I'm a web developer and designer based in Budapest, Hungary. In recent years, I've documented hundreds of solutions I came across during development. This site is an archive for useful code snippets on WordPress, Genesis Framework and WooCommerce. If You have any questions related to WordPress development, get in touch!

Primary Sidebar

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