我不知道,不工作!
-i有用户的表格帖子
我想要没有刷新页面的显示帖子使用ajax
<form class="posting" method="POST" autocomplete="off"
action="createpost.php">
<textarea name="text" class="textarea" ></textarea>
<button class="btn-ajouter" type="submit" name="ajouter" value="ajouter">ajouter</button>
</form>
//代码mysql同一页面
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
while($row=$stmt->fetch() )
{
?>
<div class="allpost">
<?php
echo $row['post'].'<br>' ;
?>
</div>
<?php
}
?>
(页面索引中存在jquery)()
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'createpost.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
- 但没有工作
答案 0 :(得分:0)
似乎您试图在用户提交表单的同一页面上显示信息。我建议你把php代码放在一个单独的文件中,然后用javascript在页面的某处打印。这样的示例代码将是这样的:
您当前页面上的Javascript代码
<script>
$(function () {
// I actually agree with Lawrence Cherone's suggestions here, so i'm including them
$('form.posting').on('submit', function (e) {
form_data = $(this).serialize()
e.preventDefault();
$.ajax({
type: 'post',
url: 'separate.php',
data: form_data,
success: function (response) {
//then you can have the server output as an object
response = JSON.parse(response);
//And print it somewhere, for example:
$('#someDiv').html(response.whatever);
}
});
});
});
</script>
php的代码在单独的文件中
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
$row = $stmt->fetch();
echo json_encode($row['post']);
答案 1 :(得分:0)
更改此按钮。因为你想运行一个AJAX调用它不应该是一个提交。
<button class="btn-ajouter" type="submit" name="ajouter" value="ajouter">ajouter</button>
到这个
<button class="btn-ajouter" id="ajouter" name="ajouter" value="ajouter">ajouter</button>
并从
更改您的JQuery$('form').on('submit', function (e) {
到
$('#ajouter').on('click', function (e) {
此外,您不需要e.preventDefault();
答案 2 :(得分:0)
更改此表单
<form class="posting" method="POST" autocomplete="off" onSubmit="return false">
<textarea name="text" id="text" class="textarea" ></textarea>
<button class="btn-ajouter" type="submit" id="ajouter" name="ajouter" value="ajouter">ajouter</button>
</form>
Ajax Goes Here,
$(function(){
$("#ajouter").click(function(){
var text=$("#text").val();
$.ajax({
url:"createpost.php",
method:"POST",
data:{text:text},
cache:false,
success:function(data){
$("#result").load(location.href+ "#result");
}
});
});
});
PHP&amp; HTML代码在这里
<div id="result">
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
while($row=$stmt->fetch() )
{
?>
<div class="allpost">
<?php
echo $row['post'].'<br>' ;
?>
</div>
<?php
}
?>
</div>