我的ajax表格没有提交

时间:2015-03-24 09:43:26

标签: javascript php jquery ajax forms

昨天我被其他用户建议开始研究Ajax编码以提高我的应用程序开发技能。

我正在测试表单提交。但是我的表格没有提交。我只是ajax的新手所以我一直在关注如何在线进行ajax的一些教程,所以任何帮助都会受到赞赏。

<html>
    <script type="text/javascript"  src="../scripts/jquery.1.11.2.min.js">    </script> 
    <form id="form" action="" method="POST">
        <textarea id="question" name="question" style="width: 200px; height: 200px; resize: none;"></textarea>
        <button id="formsubmit"> Submit</button>
    </form>
    <textarea id="response" style="width: 200px; height: 200px; resize: none;"></textarea>
    <script>
        $(document).ready(function(){
            $('#formsubmit').on("click",function(){
                $.post("submit.php", { question: $('#question').val() }, function(data) {
                    $('#response').html(data);
                });
            });
        });
    </script>
</html>

我的目标是获取用户输入并将其显示在其下方的textarea中。我不希望页面刷新。

我要处理的PHP代码是:

<?php
    $q = $_POST['question'];
    echo $q;
?>

2 个答案:

答案 0 :(得分:3)

而不是使用$('#formsubmit').on("click",function(){点击事件,请使用此:

$('#form').on("submit",function(e){
  e.preventDefault();//prevent default submission
  //your code of ajax

您应该使用<input type="submit"代替<button id="formsubmit"> Submit</button>

Working Example

答案 1 :(得分:0)

不必更改按钮输入元素。你可以尝试这个

<html>
    <script type="text/javascript"  src="http://code.jquery.com/jquery-latest.min.js">    </script>
    <form id="form" action="" method="POST">
        <textarea id="question" name="question" style="width: 200px; height: 200px; resize: none;"></textarea>
        <button id="formsubmit"> Submit</button>
    </form>
    <textarea id="response" style="width: 200px; height: 200px; resize: none;"></textarea>
    <script>
        $(document).ready(function(){
            $('#formsubmit').on("click",function(e){
                e.preventDefault();  **// need to add this line only**

                $.post("submit.php", { question: $('#question').val() }, function(data) {
                    $('#response').html(data);
                });
            });
        });
    </script>
</html>

<?php
    $q = $_POST['question'];
    echo $q;
?>