'switching from ajax function to fetch

I have a little ajax function that return a url in a modal window. I have been told that the fetch API is better. I cant find a way to do the equivalent to what I already have. Can anyone give me an example of some thing similar to

function loadDoc(url) {
  var xhttp = new XMLHttpRequest()
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById('results').innerHTML = this.responseText
    } else
      document.getElementById('results').innerHTML =
        '<div class="loader" style="display: flex; align-items: center; justify-content: center;padding: 150px 0;">' +
        '<img src="/eigg/img/ajax-loader.gif" alt="Smiley face" style="width: 50px;height: auto;background-repeat: no-repeat;"></div>'
  }

  xhttp.open('POST', url, true)
  xhttp.send()
}

Much appreciated, I find the docs quite hard to understand. Also would be nice to know why fetch is "better" than ajax



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source