David Smith David Smith - 5 months ago 9
Ajax Question

Used AJAX to update webpage - how do I change the URL too?

I've used the following tutorial: http://www.w3schools.com/ajax/default.asp

I'm using it to change the page async - however, I also want to make it so that the new URL is generated

(at the moment when a user clicks on a button it adds a # to the URL while displaying a different page, how do I make it so that the URL reflects the page that was added but remain the update async?)

HTML :

<a href="#" onclick="loadDoc('{{site.url}}/webpage.html')" id="#my-link"> Use “Just Enough” </a></h5>


JS :

<script type="text/javascript">
function loadDoc(contentURL) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("prinDesc").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", contentURL, true);
xhttp.send();
}
</script>

Answer

You'll want to use the History API in the browsers where it is supported.

Updated loadDoc function:

function loadDoc(contentURL) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("prinDesc").innerHTML = xhttp.responseText;

      window.history && window.history.pushState({}, '', contentURL);
    }
  };
  xhttp.open("GET", contentURL, true);
  xhttp.send();
}

Hope that helps!