【问题标题】:Submit ajax form without page refresh php提交ajax表单而不刷新页面php
【发布时间】:2017-04-09 03:54:04
【问题描述】:

我的 index.php 中有这个表单和 ajax 调用-

 <form method='post' id='saleForm' >
    <input type='text' name='addCustomer' class='addInput' id='adlastname' placeholder='customer last name'>
    <input type='text' name='addYear' class='addInput'  id='adYear' placeholder='year'>
    <input type='text' name='addMake' class='addInput'  id='adMake' placeholder='make'>
    <input type='text' name='addModel' class='addInput'  id='adModel' placeholder='model'>
    <input type='text' name='addGross' class='addInput'  id='adGross' placeholder='front gross'>
    <input type='hidden' name='Id' value='<?php echo $id;?>'>
    <input type='submit' name='subSale'  id='subSale' value='Save' >
</form>

<script>
    $("form").submit(function(e) {
    var url = "add.php"; // the script where you handle the form input.

$.ajax({
       type: "POST",
       url: url,
       data: $("form").serialize(), // serializes the form's elements.
       success: function(data)
       {
           alert(data); // show response from the php script.
       }
     });

e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>

我正在尝试使用 add.php 将其提交到数据库 -

$cust = $_POST['addCustomer'];
$addMake = $_POST['addMake'];
$addModel = $_POST['addModel'];
$addYear = $_POST['addYear'];
$addGross = $_POST['addGross'];
$subSale = $_POST['subSale'];
$soldDate = date('m/d/yy');

if(isset($subSale)){
    $sql = "INSERT INTO `$sold_table` ( `Id`,`Customer`, `Year`, `Make`, `Model`, `FrontGross`, `SoldDate` ) VALUES (NULL,'$cust', '$addYear', '$addMake', '$addModel', '$addGross', '$soldDate')";
    if (mysqli_query($conn, $sql)) {
        echo 'success!';
    } else {
       echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }
}

当我单击“保存”按钮时,它会显示空警报,并且由于某种原因没有推送数据。知道我在哪里出错了吗?我知道插入是正确的,因为当我不使用 ajax 调用而只使用表单操作时它可以工作..

【问题讨论】:

  • 嗯,你期望输出是什么?你没有回应任何关于成功的事情。那么,数据到达数据库了吗?
  • 是的,只是想把数据放到数据库中
  • 这至少解释了空警报
  • 另外,我不会将 Id 传递给插入查询,而是让 MySQL 执行 auto_increment。
  • 我看到了问题。 Ajax 请求不使用转售按钮。由于是jQuery提交的。

标签: php jquery ajax forms submit


【解决方案1】:

使用 jQuery 提交表单时,不使用提交按钮。因此,一旦 PHP 接收到发布的数据,它将变为空。 您的脚本正在检查 $subSale 以执行查询,但现在失败了。

尝试提供一个名为 SubSale 的隐藏输入,它会再次起作用。另一种解决方案是根据您自己的建议删除整个 if 语句。

if(isset($subSale)){

【讨论】:

    猜你喜欢
    • 2013-07-10
    • 2014-03-03
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    相关资源
    最近更新 更多