使用Ajax和PHP发送表单数据而不刷新页面和URL路径。

huangapple go评论108阅读模式
英文:

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="输入内容" 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">添加评论</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("评论为空!");
        } 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 = "评论为空!";
    }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 = "发生了一些错误!";
            // printf("Errormessage: %s\n", mysqli_error($con));
        }
    }
}

控制台错误。

英文:

Its very common question all over the internet but I don't know how to fix this problem. I have a comment system, where users can post comments. The problem is when someone posts comment on the 10th post of the page, by submitting the form they redirect to the top of the page, which i don't want. I want the comment to be sent successfully and the user must be on the same post. I hope i can understand you all experienced developers.

HTML FORM

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;form id=&quot;form&quot; action=&quot;&quot; method=&quot;post&quot;&gt;
   &lt;div class=&quot;input-group mb-3&quot;&gt;
     &lt;img class=&quot;p-1 m-0&quot; src=&quot;images/&quot; width=&quot;35&quot; height=&quot;35&quot; alt=&quot;&quot;&gt;
      &lt;input name=&quot;post_comment&quot; id=&quot;add_comments&quot; type=&quot;text&quot; autofocus class=&quot;form-control pl-3 pr-3&quot; placeholder=&quot;type somethign&quot; aria-label=&quot;Recipient&#39;s username&quot; aria-describedby=&quot;button-form&quot;&gt;
      &lt;div class=&quot;input-group-append&quot;&gt;
        &lt;button class=&quot;btn btn-secondary&quot; type=&quot;submit&quot; name=&quot;submit_comment&quot; id=&quot;button-form&quot;&gt;Add Comment&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/form&gt;

<!-- end snippet -->

JavaScript code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

&lt;script&gt;  
$(document).ready(function(){  
  $(&#39;#button-form&#39;).click(function(){
      
       var add_comments = $(&#39;#add_comments&#39;).val();
       if(add_comments == &#39;&#39;)  
       {  
            $(&#39;#error_msg&#39;).html(&quot;Comments blank!&quot;);  
       }  
       else  
       {  
    $(&#39;#error_msg&#39;).html(&#39;&#39;);  
    $.ajax({  
         url:&quot;index.php&quot;,  
         method:&#39;post&#39;,  
         data:{add_comments:add_comments},  
         success:function(data){  
              $(&quot;form&quot;).trigger(&quot;reset&quot;);  
              $(&#39;#succ_msg&#39;).fadeIn().html(data);  
              setTimeout(function(){  
                   $(&#39;#success_message&#39;).fadeOut(&quot;Slow&quot;);  
              }, 2000);  
         }  
    });  
       }  
  });  
});  
&lt;/script&gt; 

<!-- end snippet -->

PHP Query:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

if(isset($_POST[&#39;submit_comment&#39;.$ansRow[&#39;id&#39;]])){
    $comments = $_POST[&#39;post_comment&#39;.$ansRow[&#39;id&#39;]];

    if(empty($comments)){
        $cError = &quot;Wrote nothing in comments!&quot;;
    }else{
        $comments = mysqli_real_escape_string($con,$_POST[&#39;post_comment&#39;.$ansRow[&#39;id&#39;]]);

        $cQuery = &quot;INSERT INTO `qa-comments` (posted_at,updated_at,user_id,answer_id,question_id,comments_text)
        VALUES
        (now(),now(),&#39;&quot;.$_SESSION[&#39;id&#39;].&quot;&#39;,&#39;$ansId&#39;,&#39;$qId&#39;,&#39;$comments&#39;)&quot;;

        if(mysqli_query($con,$cQuery)){
           // header(&#39;refresh:0s&#39;);
        }else{
            $cError = &quot;Something went wrong!&quot;;
          //  printf(&quot;Errormessage: %s\n&quot;, mysqli_error($con));
        }
    }

}

<!-- end snippet -->

console erros.[![enter image description here][1]][1]

答案1

得分: 1

你目前没有阻止表单执行其默认行为。当你点击类型为"submit"的按钮时,表单将被发送到<form action="some_url"></form>指定的页面,或者发送到相同的页面(如果该字段为空)。

这将阻止页面重新加载并执行你的JavaScript代码。

英文:

You do not currently prevent the form from executing it's default behavior. When you click the button of type="submit" the form get's sent to the page specified in &lt;form action=&quot;some_url&quot;&gt;&lt;/form&gt; or to the same page, if that is empty

$(document).ready(function(){  
  $(&#39;#form&#39;).on(&#39;submit&#39;, function(){
    event.preventDefault()
      
    var add_comments = $(&#39;#add_comments&#39;).val();
    if(add_comments == &#39;&#39;)  
    {  
         $(&#39;#error_msg&#39;).html(&quot;Comments blank!&quot;);  
    }  
    else  
    {  
    $(&#39;#error_msg&#39;).html(&#39;&#39;);  
    $.ajax({  
         url:&quot;index.php&quot;,  
         method:&#39;post&#39;,  
         data:{add_comments:add_comments},  
         success:function(data){  
              $(&quot;form&quot;).trigger(&quot;reset&quot;);  
              $(&#39;#succ_msg&#39;).fadeIn().html(data);  
              setTimeout(function(){  
                   $(&#39;#success_message&#39;).fadeOut(&quot;Slow&quot;);  
              }, 2000);  
         }  
    });  
       }  
  });  
});

This will prevent the reloading of the page and execute your javascript instead

huangapple
  • 本文由 发表于 2020年7月30日 03:49:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63161413.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定