How to update a DIV with Ajax/JS?

Asked

Viewed 2,826 times

4

I am in the development of a page, but I am completely secular in the matter of JS...

The site has the div with the ID #content, and inside it a refresh button. How can I make it so when someone clicks it refreshes only on the div, not the whole page?

I’m currently using the code:

<img src="images/refresh.png" onclick="window.location.reload()" style="cursor: pointer; position: absolute; right: 10px; top: 10px;"/>

But he cuts the whole page...

Thank you in advance for your help!

1 answer

4


Rodrigo, to update a page by AJAX, you will first need a URL that serves you the partial content that will feed your div.

for the purpose of this example, I will use the tag <template> and the method URL.createObjectURL to create a menmoria URL.

Once you have set your URL, then we’ll have to use the object XMLHttpRequest to carry out the requisition AJAX (Asynchronous JavaScript and XML), although both the object and the technology mention XML, she can also serve HTML, JSON and others.

var tmpl = document.getElementById("tmplContent").innerHTML;
var blob = new Blob([tmpl], { type: "text/html" });
var url = URL.createObjectURL(blob);

var updateContent = document.getElementById("updateContent");
var content = document.getElementById("content");

updateContent.addEventListener("click", function (event) {
  var request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.addEventListener("readystatechange", function (event) {
    if (request.readyState == 4 && request.status == 200) {
      content.innerHTML = request.responseText
    }
  });
  request.send();
});
<div id="content">
</div>
<input id="updateContent" type="button" value="Atualizar Conteudo" />

<template id="tmplContent">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras laoreet aliquam ex vel eleifend. Aenean hendrerit cursus fermentum. Nam ornare imperdiet odio, non hendrerit risus eleifend vel. Nam nec augue consectetur, condimentum nulla ut, lacinia odio. Etiam tempus ligula ac accumsan tempus. Sed a diam non purus sodales tincidunt. Proin accumsan suscipit facilisis. Cras in placerat nulla. Ut eleifend massa eget gravida vestibulum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
  </p>
</template>

note that on the return of Xmlhttprequest, I am checking two properties, readyState (which determines which step is the request) and the status (which tells the status of the request).

It follows below a small Glosario for the readyState:

  • 0 Request not sent
  • 1 Requisition Sent
  • 2 Headers received (may be useful for a request with Http Method HEAD)
  • 3 Partially loaded (responseText partially available)
  • 4 Complete (completed request)

the HTTP status code 200 means the request has been successfully completed, you can see the other status in Http Statuses, but the most common are 301 (Moved), 400 (Ill-formed requisition), 401 (unauthorized), 403 (forbidden), 404 (Undetected), 500 (Server error) and 501 (unfulfilled).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.