<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
</head>
<body>
<div id="all-comments"></div>
<input type="hidden" name="page_id" value="1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
let page_id = $('input[name="page_id"]').val();
$.ajax({
url: 'vender/show_comment.php',
type: 'POST',
data: {
page_id: page_id
}
});
setTimeout(function() {
$("#all-comments").load("vender/show_comment.php")
}, 1000);
});
</script>
</body>
show_comment.php
<?php
$page_id=$_POST['page_id'];
if(empty($page_id))
$str="I'm empty";
else
$str=$page_id;
?>
<div class="new-comment">
<p><?php echo $str?></p>
<p><?php echo $str?></p>
</div>
I take data from input and pass it through ajax, as a result, I get "I’m empty". Why doesn’t it output the input value?
Although when I receive the same data by pressing the button and send them to the server, they will not be empty. But I need to do a data offset when the page loads
2
Answers
You have to wait for the response:
You are making two different requests.
The first request is a POST request, with a payload, but you ignore the response.
The second request is a GET request, without a payload, and you drop the response into the all-comments element.
You haven’t done anything to persist the data between two requests.
You could remove the
$.ajax
call entirely and make yourload
call a POST request and include the data there:The data still won’t be persisted for subsequent GET requests which is generally a desirable feature of comment systems.
To do that you’ll need to store the data somewhere (a database is the usual choice) and then retrieve it in subsequent requests.
Rough pseudo-code would look something along the lines of: