1
1
1234212022-04-20 15:23:17
AJAX
123421, 2022-04-20 15:23:17

Update div content on button without page reload?

Hello, how can I update the content of a div on a button without reloading the page (just refresh)? I am a beginner, there are many different solutions on the Internet, but there is also a lot of water in these solutions. Tell me please

<button class="test1" id="test" onclick="">Обновить</button>

<div class="soderzhimoye">
<?php the_title(); ?>
<?php the_content(); ?>
</div>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nadim Zakirov, 2022-04-20
@123421

An example of a function for selectively updating content:

async function elementUpdate(selector) {
  try {
    var html = await (await fetch(location.href)).text();
    var newdoc = new DOMParser().parseFromString(html, 'text/html');
    document.querySelector(selector).outerHTML = newdoc.querySelector(selector).outerHTML;
    console.log('Элемент '+selector+' был успешно обновлен');
    return true;
  } catch(err) {
    console.log('При обновлении элемента '+selector+' произошла ошибка:');
    console.error(err);
    return false;
  }
}

Call the elementUpdate() function , passing inside it the CSS selector of the element you want to update. For example, if you want to update a block that has the soderzhimoye class , then just do: If you want to bind this action to a button, you can do this:
elementUpdate('.soderzhimoye');
<button onclick="elementUpdate('.soderzhimoye');">Нажми меня, чтобы обновить блок</button>

N
Ne7Le4Der, 2022-04-20
@Ne7Le4Der

https://codesandbox.io/s/nameless-forest-cefirg

A
Artem Gvozdev, 2022-04-20
@arty23_03

it's called ajax

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question