Update data on a page without refreshing
This is typically achieved with a technique called AJAX. This technique loads data asynchronously (in the background) so it can update your content without needing to reload the page.
The easiest way to implement AJAX is with the jQuery load()
method. This method provides a simple way to load data asynchronous from a web server and place the returned HTML into the selected element. The basic syntax of this method is: $(selector).load(url, data, complete);
where the arguments are:
selector
the existing HTML element you want to load the data intourl
a string containing the URL to which the request is sentdata
(optional) a plain object or string that is sent to the server with the requestcomplete
(optional) a callback function that is executed when the request completes
The required URL parameter specifies the URL of the file you want to load.
The optional data parameter allows you to specify data (i.e. key/value pairs) that is sent to the web server along with the request. The optional complete parameter can be used to reference a callback function. The callback is fired once for each selected element.
A visualisation:
A simple example of using load()
, where we load data dynamically when a button is pressed:
DEMO
// no need to specify document ready
$(function(){
// optional: don't cache ajax to force the content to be fresh
$.ajaxSetup ({
cache: false
});
// specify loading spinner
var spinner = "<img src='http://i.imgur.com/pKopwXp.gif' alt='loading...' />";
// specify the server/url you want to load data from
var url = "http://fiddle.jshell.net/dvb0wpLs/show/";
// on click, load the data dynamically into the #result div
$("#loadbasic").click(function(){
$("#result").html(spinner).load(url);
});
});
If you don't want to use the jQuery library, you can also use plain Javascript. Loading content is slightly more difficult that way. Here is an example of how to do it with javascript only.
To learn more about AJAX, you can take a look at https://www.w3schools.com/xml/ajax_intro.asp
Refresh data without reloading the page
Assuming those DIVs hold the number of hearts, if the response of the target page is the new number of hearts then:
success: function(data) {
targetElement.find(".comments-sub-header__item-icon-count").html(data)
}
elsewhere if you want to add +1 to current number regardless of server response:
success: function() {
var current= parseInt(targetElement.find(".comments-sub-header__item-icon-count").html());
targetElement.find(".comments-sub-header__item-icon-count").html(current+1)
}
Footnote: as the ajax request is nested inside the click function, the targetElement in my codes is the clicked element. You may get it in defferent ways e.g.
$('.like-button').on('click', function(event) {
var targetElement=$(this);
....
}
automatically updates the table without refreshing/reloading the page
You just have to add it to the page, simple as that actually. Something like this (since you are using jquery) should get you started:
I am going to have to make assumptions about the way your page is laid out. Going to assume it is a table with the class "mytable".
Inside your success: function(data){
part :
$('.mytable').append(`
<tr>
<td>${studentNumberId}</td>
<td>${studentFullName}</td>
<td>${studentEmail}</td>
<td>${studentYearBlock}</td>
</tr>
`);
This should get you started on understanding the concept.
Display Updated table without refreshing or reloading page
You can pass this
as well inside your delete_data
function where this
refer to current element clicked i.e : your button . Then , inside success function use this to hide your .product
element.
Demo Code:
function delete_data(d, el) {
var id = d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
/* $.ajax({
type: "post",
url: "products.php",
data: {
id: id
},
success: function() {*/
//use this then remove closest product tr
$(el).closest(".product").animate("fast").animate({
opacity: "hide"
}, "slow");
/* }
});*/
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="bootstrap-data-table" class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
1
</td>
<td>
abs
<td>
1222
</td>
<td><a href="update_product.php?id=1"><span class="badge badge-success"><i class="ti-pencil"></i></span></a>
</td>
<td>
<!--pass `this` inside fn-->
<button class="remove badge badge-danger" onclick="delete_data('1',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
12
</td>
<td>
abs1
<td>
12221
</td>
<td><a href="update_product.php?id=2"><span class="badge badge-success"><i class="ti-pencil"></i></span></a>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data('2',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
</tbody>
</table>
Display and update data without refreshing
As mentioned in comment your problem is only related to your code assuming a wrong data format (just console.log data.length would demonstrate it)
And no, this will not trigger a page reload. Your code will work with the DOM API to manipulate the barely empty page that has been loaded as soon as your data is available in your fetch callback (assuming that your file is available along your html file on an HTTP server).
As a side note, you could perform your appends in a document fragment in order to build your element out of the DOM and append when every thing is ready.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
</head>
<body>
<h1>test</h1>
<div id="myData"></div>
<script>
fetch("data.json")
.then((response) => response.json())
.then(appendData)
.catch(console.error);
function appendData(data) {
const dataFragment = document.createDocumentFragment();
for (const user of Object.values(data.exp)) {
dataFragment.appendChild(createUserElement(user));
}
document.getElementById("myData").appendChild(dataFragment);
}
function createUserElement(user) {
const div = document.createElement("div");
div.innerHTML = `
name: ${user.name} number: ${user.number} age: ${user.age} description: ${user.description} age: ${user.age_float}
`;
return div;
}
</script>
</body>
</html>
Which can be tested assuming that http-server is available on your machine by running
http-server -p 8000 .
In your working directory and then visiting http://localhost:8000/ex.html
refresh a same page without reloading?
For a messaging app, it's better to not reload the page, instead use Ajax/fetch and just call your get-messages request, then show messages in the page,
for example:
const getMessages = ()=>{
fetch("https://jsonplaceholder.typicode.com/comments") // use your messages request url, this is a sample
.then((response) => response.json())
.then((messages) => {
let messagesHtml = "";
for (var message of messages) {
messagesHtml += `<div>${message.name}</div>`; // use your message html structure here
}
let messagesContainer = document.getElementById("messagesContainer");
messagesContainer.innerHTML = messagesHtml;
})
.catch((err) => console.log(err));
}
setInterval(getMessages, 3000);
<div id="messagesContainer"></div>
how to page without refresh show data in javascript to run every 2-5 minute
Window setInterval() Method
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
In your case you try it.
setInterval(loaddata, 5000);
Tip: 1000 ms = 1 second.
how to delete all data and the update the page without refreshing using useEffect
Some suggestions regarding backend:
router.delete("/", (req, res) => {
Item.deleteMany({}, (err) => {
if (err) {
response.status(500);
} else {
(res) => res.json({ success: true });
}
});
});
Should be res.status(500)
instead of response.status(500)
Check your route, this one seems to be incorrect, try /itmes
or maybe /api/items
(res) => res.json({ success: true });
this part also seems incorrect, should be:
else {
res.json({ success: true }); // or res.json([])
}
Good luck!)
How do I refresh a div with AJAX without refreshing the whole page?
You can create another resource for the content of the <div>
to refresh (that can be another php script if using PHP, or the same script as the whole page but with some params...). Then:
function refresh () {
$.ajax({
url: '/div/to/refresh.php',
success: function(data) {
$('.torefreshdiv').html(data);
}
});
}
Related Topics
Regex to Check the String Contains Only Letter and Numbers But Not Only Numbers
How to Export Data in Multiple Sheets in PHP
Clear the Form Field After Successful Submission of PHP Form
How to Insert Md5 Hash Value in Ms SQL Server
Codeigniter - Call to a Member Function Result() on Boolean In
Reference - What Does This Symbol Mean in PHP
Send Attachments With PHP Mail()
Show a Number to Two Decimal Places
What Are Long-polling, Websockets, Server-sent Events (Sse) and Comet
How to Convert Array to Simplexml
PHP - Ssl Certificate Error: Unable to Get Local Issuer Certificate
MySQL Great Circle Distance (Haversine Formula)
How to Ping a Server Port With PHP
Laravel, Sync() - How to Sync an Array and Also Pass Additional Pivot Fields