O
O
omerkhan2021-11-05 16:48:28
AJAX
omerkhan, 2021-11-05 16:48:28

How to update block using ajax?

Hello. How to update one block without reloading the whole page? I know there are many such questions on the Internet, but the code that I copied from the Internet did not work for me. Let's say I have:

<div id = "block">
...
</div>

How do I update this block, let's say every second?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-11-05
@omerkhan

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.dir(err);
    return false;
  }
}

Call the elementUpdate() function , passing inside it the CSS selector of the element you want to update. For example, if you take a block that has an id equal to block , then it is enough to do: If you want to do it cyclically, every second, then you can use while :
elementUpdate('div#block');
// Запуск асинхронного кода:

(async function() {
  
  // Бесконечный цикл:
  
  while (true) {
    
    await elementUpdate('div#block'); // Обновляем блок
    
    // Выжидаем 1000 миллисекунд, а потом код внутри while выполняется вновь:
    await new Promise(function(success) { setTimeout(success, 1000); });
    
  }

})();

PS But they don't usually do this, but if you really really need it, you can use this frontal method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question