Hi everyone! I am currently developing a website and I would like some areas to be refreshed when one click on a button. Can anyone help?

Dani AI

Generated

As suggested, AJAX is the right approach. For : keep it simple — have your server return either a small HTML fragment (ready to inject) or JSON (to render client-side), then fetch that fragment when the user clicks a button and replace the target container. The modern, lightweight way is the Fetch API; use jQuery only if your project already depends on it.

A minimal pattern (data attributes + event delegation, cache-busting, error handling):

<button data-url="/widget/price" data-target="#price" id="refreshPrice">Refresh</button>
<div id="price" aria-live="polite">...</div>

<script>
document.addEventListener('click', function(e) {
  var btn = e.target.closest('[data-url]');
  if (!btn) return;
  var target = document.querySelector(btn.dataset.target);
  if (!target) return;

  var url = btn.dataset.url + '?_=' + Date.now(); // simple cache-buster
  fetch(url, { credentials: 'same-origin' })
    .then(function(res) {
      if (!res.ok) throw new Error(res.status + ' ' + res.statusText);
      return res.text();
    })
    .then(function(html) {
      target.innerHTML = html; // if HTML comes from a trusted source
    })
    .catch(function(err) {
      console.error('Refresh failed:', err);
      // show a user-friendly message or retry here
    });
});
</script>

If you use jQuery, a one-liner is $('#price').load('/widget/price'); — remember to add a cache-buster if needed.

Things to watch for:

  • Return only the fragment you need (not a full HTML page) or return JSON and build the DOM client-side.
  • Sanitize or escape server output if it contains user content to avoid XSS.
  • If your server requires CSRF tokens, send them as headers (fetch headers option).
  • Use aria-live or focus management to keep updates accessible.
  • Test error states and slow connections; show a spinner or retry logic.

See the Fetch API usage notes on MDN for details: Using Fetch.

Recommended Answers

All 2 Replies

The concept/technology you are looking for is ajax. Check out this tutorial site:. Then post any specific questions you have.

Thank you scrappedcola. I am having a look at that website and I will get back to you in case of any other issue

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.