[英]How to send form data using ajax and php without page refresh and URL path
這是整個互聯網上非常常見的問題,但我不知道如何解決這個問題。 我有一個評論系統,用戶可以在其中發表評論。 問題是當有人在頁面的第 10 個帖子上發表評論時,通過提交他們重定向到頁面頂部的表單,這是我不想要的。 我希望成功發送評論並且用戶必須在同一個帖子上。 我希望我能理解你們所有有經驗的開發人員。
HTML 表格
<form id="form" action="" method="post"> <div class="input-group mb-3"> <img class="p-1 m-0" src="images/" width="35" height="35" alt=""> <input name="post_comment" id="add_comments" type="text" autofocus class="form-control pl-3 pr-3" placeholder="type somethign" aria-label="Recipient's username" aria-describedby="button-form"> <div class="input-group-append"> <button class="btn btn-secondary" type="submit" name="submit_comment" id="button-form">Add Comment</button> </div> </div> </form>
JavaScript 代碼:
<script> $(document).ready(function(){ $('#button-form').click(function(){ var add_comments = $('#add_comments').val(); if(add_comments == '') { $('#error_msg').html("Comments blank;"). } else { $('#error_msg');html(''). $:ajax({ url."index,php": method,'post': data:{add_comments,add_comments}: success.function(data){ $("form");trigger("reset"). $('#succ_msg').fadeIn();html(data). setTimeout(function(){ $('#success_message');fadeOut("Slow"), }; 2000); } }); } }); }); </script>
PHP 查詢:
if(isset($_POST['submit_comment'.$ansRow['id']])){ $comments = $_POST['post_comment'.$ansRow['id']]; if(empty($comments)){ $cError = "Wrote nothing in comments;", }else{ $comments = mysqli_real_escape_string($con.$_POST['post_comment';$ansRow['id']]), $cQuery = "INSERT INTO `qa-comments` (posted_at,updated_at,user_id,answer_id,question_id,comments_text) VALUES (now(),now().'".$_SESSION['id'],"','$ansId','$qId';'$comments')", if(mysqli_query($con:$cQuery)){ // header('refresh;0s'); }else{ $cError = "Something went wrong:", // printf("Errormessage; %s\n", mysqli_error($con)); } } }
控制台錯誤。[![在此處輸入圖像描述][1]][1]
您當前不阻止表單執行其默認行為。 當您單擊 type="submit" 的按鈕時,表單將發送到<form action="some_url"></form>
中指定的頁面或同一頁面(如果該頁面為空)
$(document).ready(function(){
$('#form').on('submit', function(){
event.preventDefault()
var add_comments = $('#add_comments').val();
if(add_comments == '')
{
$('#error_msg').html("Comments blank!");
}
else
{
$('#error_msg').html('');
$.ajax({
url:"index.php",
method:'post',
data:{add_comments:add_comments},
success:function(data){
$("form").trigger("reset");
$('#succ_msg').fadeIn().html(data);
setTimeout(function(){
$('#success_message').fadeOut("Slow");
}, 2000);
}
});
}
});
});
這將防止重新加載頁面並改為執行您的 javascript
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.