使用AJAX和警告重新加载时避免重新提交表单:无法修改标题FIX

时间:2017-08-29 10:50:49

标签: javascript php jquery ajax mysqli

我在这里遇到的问题是在刷新页面时重新提交表单。现在我知道网上有很多答案可以解决我上面提到的问题。但是我的问题有什么不同之处在于我使用ajax来提交表单,因此表单不会重定向,只会更新其中的一部分。由于我不希望页面重定向,因此我无法使用post / redirect / get方法。

这是我的代码:

HTML:

 <form method="post" onsubmit="return submitdata();">
   <textarea maxlength="3000" id="profile-post" name="profile-post" placeholder="Write a post..." rows="3" cols="65" required></textarea>
   <input type="submit" value="Post">
 </form>

脚本:

 function submitdata()
        {
         var post=document.getElementById( "profile-post" );

         $.ajax({
          type: 'post',
          url: 'page.php',
          data: {
           post:post
          }
         })
         };

PHP:

if(isset($_POST['profile-post'])){
  $post = $_POST['profile-post'];
  mysqli_query($dbc,"INSERT INTO make_post (post, time, date, user_id) VALUES ('$post', CURTIME(), CURDATE(), '$id_profile')"); 
  }

}

有没有其他方法可以达到我在网上搜索时找不到的预期结果。

感谢。

2 个答案:

答案 0 :(得分:0)

所以你在你的表单中输入你想要的任何内容,用jquery获取它,用ajax将它发送到php页面并将其查询到数据库中,然后将其动态插入到... table或者其他内容中。 您的代码或解释的大部分内容都缺失了。这是我能给予的最多。

<form method="post">  
   <textarea maxlength="3000" id="profile-post" name="profile-post" placeholder="Write a post..." rows="3" cols="65" required></textarea>
   <button type="button" value="Post">
 </form>

$(document).ready(function(e){  

   var post = $('#profile-post').val();
$.ajax({
                    type:"POST" ,
                    data :{
                        'type' : 'post',
                        'id':  id,
                        'post' : post
                    },
                    url : '../allforms.php' //Php page to send data
                    }).success(function(data){
                        $('#profile-post').val('');
                        //Write code of whatever you want to load dynamically 
                               without loading
                    });

});
}

请更清楚地解释您想要的结果

答案 1 :(得分:0)

我能够通过添加

来解决这个问题
header('location:page.php');
提交表单后,在我的PHP文件中

。 我认为这将重定向到page.php,它将重新加载我想避免,因此使用ajax。但添加该行并没有重新加载整个页面。 我非常感谢大家抽出时间回答我的问题。 此外,我在使用标题时遇到错误 警告:无法修改标头信息 - 已经发送的标头.. 并通过添加

来解决
<?php ob.start();?> 

和文件的开头。

我希望这可以帮助任何有类似问题的人。感谢。