首页 > 解决方案 > 添加输入时数据库未响应表单

问题描述

所以我的数据库在按下按钮时不会将此数据添加到数据库中。我创建了一个表单,所有的 id 都是完美的,电子邮件是一个外键,所以它是从登录用户的 sessionStorage 中获取的。我需要帮助,为什么它不起作用,我不知道。当我按下提交时,页面提醒我“订单成功”,但数据没有存储在数据库中。我的 SQL 语句也确实有效,我在我的数据库中尝试过。这是我的php和js:

<?php
header("Content-Type: application/json; charset=UTF-8");
 $servername = "localhost";
 $username = "root";
 $password = "leaf123";
 $dbname = "laxmi";

 // Create Connection

 $conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn)
{
die("Connection failed:" . mysqli_connect_error());
}
else
{

// Obtain the contents

$request = file_get_contents('php://input');

// decode json so PHP can use it

$jsonRequest = json_decode($request);

// Query
$sql = "INSERT INTO checkout(email, ccName, ccNumber, month, year, cvc) VALUES ('$jsonRequest->email', '$jsonRequest->ccName', '$jsonRequest->ccNumber', '$jsonRequest->month', '$jsonRequest->year', '$jsonRequest->cvc')"




}

// Execute Query

$results = mysqli_query($conn, $sql);
echo json_encode("success");
mysqli_close($conn);

我的 javascript

$(document).ready(function () {
//When the submit button on the checkout form is pressed.
$("#SubmitOrder").on("click", function () {
    //store each individual entry into a separate variable.
    var email = sessionStorage.getItem("loggedInUser");
    var ccname = document.getElementById("ccName").value;
    var ccnum = document.getElementById("ccNumber").value;
    var month = document.getElementById("month").value;
    var year = document.getElementById("year").value;
    var cvc = document.getElementById("cvc").value;


        //create an array with the details in.
        var checkout = {
            email: email,
            ccname: ccname,
            ccnum: ccnum,
            month: month,
            cvc: cvc,
        }
        //direct the user to the login page and alert them that their registration was successful.
        alert("Your order was successful.")
        window.location.href = "../index.html"  
        //posts the JSON object to the php file so it can fill the database, and converts the checkout array into JSON so it can be read. 
        var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
})

})

标签: javascriptphpsql

解决方案


首先,在尝试将发布请求发送到 PHP 文件之前,您会显示成功消息。所以你的第一份工作是重新订购东西

var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout));
alert("Your order was successful.");
window.location.href = "../index.html";

其次,您目前没有检查来自服务器的关于请求是否成功的响应。我已经修改了 jQuery 文档https://api.jquery.com/jquery.post/中的示例

var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
  .done(function() {
    alert("Your order was successful.");
    window.location.href = "../index.html";
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

完成此操作后,您将需要考虑从 PHP 返回响应以说明查询是否有效等,但以上内容至少足以让您获得目前有效的东西 :)


推荐阅读