Ajax请求无法正常工作。没有连接到服务器

时间:2015-04-16 13:57:23

标签: javascript php jquery ajax

我创建了一个简单的联系人表单,它从文本字段中捕获数据,然后将数据转换为JSON对象,并使用Ajax发送到服务器。但我总是得到错误。成功功能无效。我认为它没有连接到服务器。

请告诉我哪里出错了。

HTML

body>
  <h1> Contact Us </h1>
  We value your feedback. Send in your questions, suggestions, ideas to help us improve our service.

  <h2 align="Center"> Search us on Google Maps</h2>
<br> 
    <br>


    <form action="contact.php" name="form" method="post">

    <br>Name :<br>

    <input type="text" name="fName" id="fName"  required >

    &nbsp; &nbsp;
   <input type="text" name="lName" id="lName"  required >
    <br> <br>
    Email: <br>

    <input type="email" name="email" id="email" required >

    <br> <br>
    Comment: <br>

    <textarea name= "comment" id = "comment" rows="8" cols="50"  ></textarea>

     <br> <br>

    Rate our Website <select name="select" id="select" >
    <option value = "1" name= "rate"> 1 </option>
    <option value = "2" name= "rate"> 2 </option>
    <option value = "3" name= "rate"> 3 </option>
    <option value = "4" name= "rate"> 4 </option>
    <option value = "5" name= "rate"> 5 </option>

    </select>

     <br> <br>
    <input type="submit" name="submit" id="submit" value="Submit">

  </form>
  </body>

的Javascript

<script>

    $(document).ready(function(){
       $("form").submit(function(){
        alert("Submitted");

        var jsonArr = {
          firstName   :document.getElementById("fName").value,
          lastName    :document.getElementById("lName").value,
          email       :document.getElementById("email").value,
          comment     :document.getElementById("comment").value,
          rate        :document.getElementById("select").value
        };


          $.ajax({
              url       : "contact.php",
              type      : "POST",
              data      : JSON.stringify(jsonArr),
              dataType  : "json",
              success   : function(data){
                console.log("This is working", data);
              },
              error     : function (error){
                alert("Error. not working"+ error);
                console.log("Error. not working" , error);
              }

          });

    });

});

 </script>

PHP

<html>
    <body>
    <?php
    $decode = $_POST['firstName'];
var_dump($decode);
?>
</body>
</html>

4 个答案:

答案 0 :(得分:1)

首先,尝试在网址上添加一个斜杠,使其相对于您的主机:

    $.ajax({
          url       : "/contact.php",
          type      : "POST",
          data      : JSON.stringify(jsonArr),
          dataType  : "json",
          success   : function(data){
            console.log("This is working", data);
          },
          error     : function (error){
            alert("Error: " + error);
            console.log("Error. not working" , error);
          }

      });

第二,关闭contact.php文件中的PHP标记:

<html>
    <body>
    <?php
    $decode = $_POST['firstName'];
var_dump($decode);
</body>
</html>

应该是:

<html>
    <body>
    <?php
        $decode = $_POST['firstName'];
        var_dump($decode);
    ?>
</body>
</html>

答案 1 :(得分:1)

这里有一些问题:

取消默认提交

您没有取消默认的提交事件,因此表单将以非ajax方式提交,有效地重新加载页面(假设所有内容都在contact.php完成)。

您需要以下内容:

$('form').on('submit', function(event) {
  event.preventDefault();
  ...
});

发送服务器上预期的数据类型

您不是以允许您通过$_POST访问数据的格式向服务器发送数据。你正在发送一个字符串,所以你需要阅读输入。如果要通过$_POST访问它,则需要发送一个查询字符串或(更好的是,它们自动编码...)一个对象。获取编码数据的最简单方法是使用:

...
data: $('form').serialize(),
...

或者,如果你想使用你的设置键:

...
data: jsonArr,  // sending an object is fine, jQuery will encode it correctly for you
...

PHP语法错误

你的php有如前所述的语法错误。但是,由于下一个问题,这与此无关。

仅从您的php脚本中返回json

你的php最大的问题是它返回html而不是json。正如你设定的那样:

dataType  : "json",

你的php脚本需要返回有效的json。所以除了单个json_encode()之外没有任何标签或任何回声。

因此,对于您的示例,它应仅包含:

<?php
$decode = $_POST['firstName'];
// do some more stuff?

echo json_encode($decode);
exit;

答案 2 :(得分:0)

尝试更改你的JS(见下文)。触发onclick事件,并防止可能重复的submisssions默认并重构您的json。看看是否有效。

<script>
    $(document).ready(function() {
        $("#submit").click(function(e) {
            e.preventDefault();
            $.ajax({
                url: "contact.php",
                type: "POST",
                data: {
                    'firstName': document.getElementById("fName").value,
                    'lastName ': document.getElementById("lName").value,
                    'email': document.getElementById("email").value,
                    'comment': document.getElementById("comment").value,
                    'rate': document.getElementById("select").value
                },
                dataType: "json",
                success: function(data) {
                    console.log("This is working", data);
                },
                error: function(error) {
                    alert("Error. not working") + error;
                    console.log("Error. not working", error);
                }

            });

        });

    });
</script>

答案 3 :(得分:-1)

为表单添加id属性并尝试此代码
  

    $(document).ready(function(){
       $("form").submit(function(){
        alert("Submitted");




          $.ajax({
              url       : "contact.php",
              type      : "POST",
              data      : $("{formid}").serialize,

              success   : function(data){
                console.log("This is working", data);
              },
              error     : function (error){
                alert("Error. not working")+ error;
                console.log("Error. not working" , error);
              }

          });

    });

});

 </script>