Tezma
Tezma

Reputation: 1

How to refresh a div using a button

So I have a "feed" of posts from a database and I want to have a button that refreshes only the div containing the posts, rather than reloading the whole page.

Upvotes: 0

Views: 119

Answers (4)

Cameron Drennan
Cameron Drennan

Reputation: 1

Ajax (short for asynchronous JavaScript and XML) is what you're looking for. You can add a button listener that will run your Ajax code which in turn can call your database query.

Your Ajax function will look similar to this:

function loadData() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
         document.getElementById("yourDivId").innerHTML = xhttp.responseText;
      }
    };
    xhttp.open("GET", "databaseQuery.php", true);
    xhttp.send();
}

Your button listener will call the Ajax function:

<button onclick="loadData()">Click me</button>

And if your are using php to query the database, just echo your result from databaseQuery.php.

Upvotes: 0

A.A
A.A

Reputation: 2713

In Jquery

 <button id="MyButton">Refresh</button>

$(document).ready(function () {
     $("#myButton").on("click", function () {
        $("#div").load("index.php")
     });
});

Upvotes: 0

luc122c
luc122c

Reputation: 439

Javascript by nature modifies content on the page so you don't have to 'refresh' the page to update it's content.

If you're using AJAX to pull in the data dynamically from perhaps an XML or JSON source, you can take a look at my examples here: http://penguin.uclan.ac.uk/~lnelson/TE2006/ex3.html

Alternatively, just Google AJAX and there are a wealth of resources out there.

Upvotes: 0

Abozanona
Abozanona

Reputation: 2285

Suppose that the div is

<div id="myContent"></div>

and you want to refresh it's content in a new html markup stored in the variable ajaxCont.

to change the content of the #myContent div

document.getElementById("myContent").innerHtml(ajaxCont);

If you want to add the content to the current content

document.getElementById("myContent").appendChild(ajaxCont);

Upvotes: 3

Related Questions