php - reload an specific div without refresh whole page
Solution:
The problem is that you're returning an entire HTML document when you use location.href
as the URL. The documentation warns:
jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as
<html>
,<title>
, or<head>
elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.
Since you're returning the <html>
element, this is being filtered out, so there's nothing to insert into #reloadable
.
Instead, you could load directly from rand.php
:
function refreshDiv()
{
$('#reloadable').load('rand.php');
}
Answer
Solution:
With the pure respect to all friends that helped me specially Barmar and Ken lee, I can not accept Barmar's answer as correct answer. Because Barmar said $('#reloadable').load(location.href + ' #reloadable');
can not run properly and mentioned some reasons. But I added
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
from Ken lee's answer and also added onclick="javascript:refreshDiv()
to my original code attached to main question and it worked. So the following code is working
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<html>
<body>
<div id="reloadable"><?php include "rand.php"; ?></div>
<button class="ref" onclick="javascript:refreshDiv();"> refresh </button>
<script>
function refreshDiv() {
$('#reloadable').load(location.href + ' #reloadable');
}
</script>
</body>
</html>
Source