Skip to content

Instantly share code, notes, and snippets.

@vamsee9
Created December 5, 2022 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vamsee9/7a6b08a5957d892171e447f83724afc9 to your computer and use it in GitHub Desktop.
Save vamsee9/7a6b08a5957d892171e447f83724afc9 to your computer and use it in GitHub Desktop.

Here is an example of how you could use HTML, CSS, and Ajax to create a page that fetches a person's name, age, and ID from an API when a button is clicked, and then hides the button after it has been clicked:

<!-- index.html -->
<html>
  <head>
    <title>Data Fetcher</title>
    <link rel="stylesheet" href="styles.css" />
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script src="index.js"></script>
  </body>
</html>
// styles.css
.hidden {
  display: none;
}
// index.js
const rootElement = document.getElementById('root');

const fetchData = async () => {
  // Fetch data from API here
  const response = await axios.get('https://example.com/api/endpoint');
  const { name, age, id } = response.data;

  // Update the page with the fetched data
  rootElement.innerHTML = `
    <p>Name: ${name}</p>
    <p>Age: ${age}</p>
    <p>ID: ${id}</p>
  `;
};

rootElement.innerHTML = `<button id="fetch-button">Fetch Data</button>`;

const fetchButton = document.getElementById('fetch-button');
fetchButton.addEventListener('click', () => {
  // Hide the button after it is clicked
  fetchButton.classList.add('hidden');

  fetchData();
});

In this example, the page includes a div element with the ID root, which is used as a container for the page's content. When the page is loaded, the index.js script is executed, which adds a "Fetch Data" button to the root element.

When the button is clicked, the fetchData function is called, which uses the axios library to fetch data from the specified API endpoint. Once the data is fetched, it is displayed on the page by updating the root element with the fetched data. The button is then hidden by adding the hidden CSS class to it.

This is just one possible way to implement this functionality using HTML, CSS, and Ajax. There are many other ways you could achieve the same result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment