添加输入时数据库不响应表单

时间:2018-11-10 21:04:54

标签: javascript php sql

因此,当按下按钮时,我的数据库不会将此数据添加到数据库中。 我已经创建了一个表单,并且所有id都是完美的,并且电子邮件是外键,因此它取自登录用户的sessionStorage。我需要帮助,为什么它不起作用,我不知道。当我按Submit时,页面警告我“订单成功”,但数据没有存储在数据库中。 我的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))
})

})

1 个答案:

答案 0 :(得分:0)

首先,您正在显示成功消息,甚至试图将发布请求发送到您的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返回响应以说明查询是否有效,等等,但是以上内容至少足以使您目前可以使用:)