javascript - 提交表单时使用 AJAX

标签 javascript php jquery ajax forms

我对使用 AJAX 进行表单提交非常陌生,并且一直在关注许多有关其使用的教程,但是我似乎无法让它在我当前的场景中工作。

我有一个模态,其中的表单链接到 PHP 脚本和一些 JQuery AJAX。

当我提交表单时,页面显示为白色,我相当确定这是由于我的 PHP 脚本中的条件逻辑造成的。

因此,当我有 $stmt->rowCount() 和条件逻辑时,它不会返回任何内容,因为脚本此时不执行任何操作。

我可以将此逻辑链接到 AJAX 成功或失败,还是必须从脚本中返回 bool 值?

我知道这可能被认为是一个愚蠢的问题,但澄清一些会很有用。

表格

<form id="userForm" method="post" action="test/process_data.php">
    <div class="form-group">
      <label for="email">First name:</label>
      <input type="text" class="form-control" name="forename" id="forename" placeholder="E.g John" required>
    </div>
      <div class="form-group">
      <label for="email">Surname:</label>
      <input type="text" class="form-control" name="surname" id="surname" placeholder="E.g Smith" required>
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" name="email" id="email" placeholder="someone@example.com">
    </div>
    <div class="form-group">
      <label for="company">Company:</label>
      <input type="text" class="form-control" name="company" id="company" placeholder="Company name">
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
    <a href="" class="btn btn-default">Just take me to the partner</a>
  </form>

AJAX 脚本

<script>

      $("#userForm").submit(function(e) {
         var forename = $('#forename').val();
         var surname = $('#surname').val();
         var email = $('#email').val();
         var company = $('#company').val();

      $.ajax({
          url: "process_data.php",
          type: "POST",
          data: {
              "forename" : forename,
              "surname" : surname,
              "email" : email,
              "company" : company
          },
          success: function(data){
            $("#forename").val('');
            $("#surname").val('');
            $("#email").val('');
            $("#company").val('');

          }
      });

        e.preventDefault(); // avoid to execute the actual submit of the form.

      }


</script>

处理数据的 PHP 脚本

if (empty($_POST["forename"]) || 
    empty($_POST["surname"]) || 
    empty($_POST["email"]) ||
    empty($_POST["company"]))
    {

    }
    else{

        $forename = $_POST['forename'];
        $surname = $_POST['surname'];
        $email_address = $_POST['email'];
        $company_name = $_POST['company'];
        $id = rand();
        $date_time = date('Y-m-d');


        try
            {
                // Construct the SQL to add a book to the database
                $sql = "INSERT INTO user_data (forename, surname, email_address, company_name, id, date_time)
                VALUES (:forename, :surname, :email_address, :company_name, :id, :date_time)";
                // Prepare the SQL and bind parameters
                $stmt = $conn->prepare($sql);
                $stmt->bindParam(':forename', $forename);
                $stmt->bindParam(':surname', $surname);
                $stmt->bindParam(':email_address', $email_address);
                $stmt->bindParam(':company_name', $company_name);
                $stmt->bindParam(':id', $id);
                $stmt->bindParam(':date_time', $date_time);
                $stmt->execute();

                // If the statement affected the database
                if ($stmt->rowCount() > 0)
                {

                }
                else{

                }

            } catch(PDOException $e){
                echo "Error: " . $e->getMessage();
            }

    }

最佳答案

在表单上使用serialize()方法来定义ajax调用中的数据属性。还添加了错误处理。

  $.ajax({
      url: "process_data.php",
      type: "POST",
      data:  $("#userForm").serialize(),
      success: function(data){
          //Successful
      },
      error: function (XMLHttpRequest, textStatus, errorThrown)
      {
           if (!window.console) console = { log: function () { } };
           console.log(JSON.stringify(XMLHttpRequest), textStatus, errorThrown);
      }
  });

关于javascript - 提交表单时使用 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42072821/

相关文章:

javascript - ajax 调用缺少参数

javascript - 如何改变:visited to its parent color on refresh of the page的颜色

javascript - Mapbox js : Changing the different latlng of a polyline based on properties

php - 实现一个按钮将信息发送到另一个 php 文件?

php项目部署新问题

jquery 取消选中带有链接的复选框

javascript - 如何在更改文档时将一个集合复制到另一台服务器

javascript - 不要在更改时渲染主干 Marionette Collection View ?

php - SQL查找匹配的OR

javascript - 检测所有图像何时加载到 Angular.js View 中