使用php和ajax提交表单

时间:2013-01-09 15:39:26

标签: php javascript html ajax

我正在尝试将ajax添加到我的表单中,这样我就可以在不刷新的情况下提交表单,但是php echo命令无效。如果我取出ajax它工作正常但刷新提交。我认为这是试图让他们一起工作的一个案例。我现在正在学习ajax所以我真的不太了解这一切。请看看我出错的地方

<script type="text/javascript"
 src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>   
<script type="text/javascript">
    $(function() {
        $('form').bind('submit', function(){
            $.ajax({
                type: "POST",
                url: "ajax.html",
                data: $("form").serialize(),
                success: function() {
                    alert("form was submitted");
                }
            });
            return false;
        });
    });
</script>

<?php
    if(isset($_POST['submit'])){
          $a=$_POST['a'];
          $b=$_POST['b'];

           echo $a.$b;
       }
?>

<html>
 <form method='POST'>
    first name:<input type="text" name="a">
    last name: <input type="text" name="b">
               <input type='submit' name='submit'>
  </form>
</html>

4 个答案:

答案 0 :(得分:3)

看着它,你发送一个ajax请求到“ajax.html”并将你的php标签放在“ajax.html”中你需要将它重命名为“ajax.php”以允许php标签工作。

答案 1 :(得分:2)

您的成功函数只会触发包含静态文本的警报。

success: function() {
    alert("form was submitted");
}

如果要查看响应数据,则必须对响应数据执行某些操作。

success: function(data) {
    alert(data);
}

答案 2 :(得分:1)

  1. 将.html更改为.php,否则将无法通过php解释器进行解析。除非你已经配置了apache来解析.html文件。
  2. 您是否正在向上述页面发出ajax请求?你知道你得到的不仅仅是$ a。$ b的回声吧?你也会得到回传的html部分。我建议创建另一个脚本并发布到那个脚本,没有表单标签。
  3. 在您的ajax请求中,您需要console.log( data )alert( data )

答案 3 :(得分:1)

可能值得注意的是,您的echo的PHP代码将不可见,因为ajax响应将获取该信息。这不是如何使用ajax的一个很好的例子,因为你没有显示ajax调用的结果。这样的事情会更有意义:

“ajax.php”PHP文件:

<?php
    if(isset($_POST['submit']))
    {
       $a=$_POST['a'];
       $b=$_POST['b'];
       //Add user name to database here or something
       die($a." ".$b); //Prevents anything after this from being returned
    }
?>

<script type="text/javascript"
 src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>   
<script type="text/javascript">
    $(function() {
        $('form').bind('submit', function(){
            $.ajax({
                type: "POST",
                url: "ajax.php",
                data: $("form").serialize(),
                success: function(data) {
                    alert("Hello " + data);
                }
            });
            return false;
        });
    });
</script>

<html>
 <form method='POST'>
    first name:<input type="text" name="a">
    last name: <input type="text" name="b">
               <input type='submit' name='submit'>
  </form>
</html>
相关问题