Glen Martin
Glen Martin

Reputation: 31

Refresh div content, without Jquery, AJAX

How do you use just plain JS to refresh the content of the an AJAX inserted div? So many examples use Jquery but I'm trying to stay light and not use Jquery. What I have so far:

-index. php the html page -livedata. php html of the section with the live data -scripts. js file with the JS

I want to refresh page every 10 seconds.

var xhr = new XMLHttpRequest();                 // Create XMLHttpRequest object

xhr.onload = function() {                       // When response has loaded
  // The following conditional check will not work locally - only on a server
  if(xhr.status === 200) {                       // If server status was ok
    document.getElementById('live').innerHTML = xhr.responseText; // Update
  }
};

xhr.open('GET', 'livedata.php', true);        // Prepare the request
xhr.send(null);                                 // Send the request

Just for reference here is index.php

    <!doctype html>

<html>

<head>
    <title>Page Title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0">
</head>

<body>
    <section id="live">
        <p>please wait... loading content</p>
    </section>
    <script src="scripts.js"></script>
</body>

</html>

Upvotes: 0

Views: 3244

Answers (1)

leonardosouza
leonardosouza

Reputation: 11

You can try this:

function getData() {
  var xhr = new XMLHttpRequest();                 // Create XMLHttpRequest object

  xhr.onload = function() {                       // When response has loaded
    // The following conditional check will not work locally - only on a server
    if(xhr.status === 200) {                       // If server status was ok
      document.getElementById('live').innerHTML = xhr.responseText; // Update
    }
  };

  xhr.open('GET', 'livedata.php', true);        // Prepare the request
  xhr.send(null);                                 // Send the request
}

setInterval(getData, 1000*10);

Upvotes: 1

Related Questions