javascript - undefined index 错误 - 如何设置折扣后的最后金额?

标签 javascript php html json

我制作了一个优惠券代码系统,供管理员创建新的优惠券。在表格上,我需要计算折扣后最后支付的金额。我写了

if(!empty($discountCode)) { 
    $amount = ($unitCost - $unitCost * $couponDiscount / 100); 
} 

在添加运费和处理付款之前。不知道对不对...

我收到 undefined index 错误 $email - $qty - $cardName - $cardAddress1 - $cardAddress2 - $cardCity - $cardState - $cardZipcode - $shippingMethod - $product - $token - $couponDiscount,很奇怪,但不适用于 $unitCost、$intRate 或 $domRate

我该如何解决这个问题?

这是我的表单 preorder.php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Stores errors:
    $errors = array();

    // Need a payment token:
    if (isset($_POST['stripeToken'])) {

        $token = $_POST['stripeToken'];

        // Check for a duplicate submission, just in case:
        // Uses sessions
        if (isset($_SESSION['token']) && ($_SESSION['token'] == $token)) {
            $errors['token'] = 'You have apparently resubmitted the form. Please do not do that.';
        } else { // New submission.
            $_SESSION['token'] = $token;
        }

    } else {
        $errors['token'] = 'The order cannot be processed. Please make sure you have JavaScript enabled and try again.';
    }

    $unitCost       = 6995;
    $intRate        = 1500;
    $domRate        = 500;

    //print_r($_POST);
    $email          = $_POST['email'];
    $qty            = $_POST['qty'];
    $cardName       = $_POST['card-name'];
    $cardAddress1   = $_POST['address'];
    $cardAddress2   = $_POST['address2'];
    $cardCity       = $_POST['city'];
    $cardState      = $_POST['state'];
    $cardZipcode    = $_POST['zipcode'];
    $shippingMethod = $_POST['shipping-method'];
    $product        = $_POST['productColor'];
    $token          = $_POST['stripeToken'];
    $couponDiscount = $_POST['couponDiscount'];

    if(!empty($discountCode)) {
        $amount = ($unitCost - $unitCost * $couponDiscount / 100);
    }

     if($shippingMethod == 'International') :
         $amount = $qty * ($intRate + $unitCost);
         $description    = ''.$qty.' - products(s) in '.$product.'(+International Shipping)';
     else:
         $amount = $qty * ($domRate + $unitCost);
         $description    = ''.$qty.' - products(s) in '.$product.'(+Domestic Shipping)';
     endif;

     // Charge the order:
     $charge = Stripe_Charge::create(array(
         "amount"          => $amount, // amount in cents, again
         "currency"        => "usd",
         "description"      => $description,
         "customer"        => $customer->id
     ));

     // Check that it was paid:
     if ($charge->paid == true) {
         $amountReadable = $amount / 100; // to add in decimal points
         echo '<div class="alert alert-success">Your card was successfully billed for $'.$amountReadable.'</div>';
         $status = "paid";
         $tracking_num = "";

表单提交是与 preorder.js 中的优惠券验证一起完成的,它运行良好并正确检查代码:

// Watch for the document to be ready:
$(document).ready(function() {

    // Watch for a form submission:
    $("#preorder").submit(function(event) {

        // Flag variable:
        var error = false;

        // disable the submit button to prevent repeated clicks:
        $('#submitBtn').attr("disabled", "disabled");

        // Check for errors:
        if (!error) {
            Stripe.card.createToken({
                number: $('.card-number').val(),
                cvc: $('.card-cvc').val(),
                exp_month: $('.card-expiry-month').val(),
                exp_year: $('.card-expiry-year').val()
            }, stripeResponseHandler);

        }

        // Prevent the form from submitting:
        return false;

    }); // Form submission

    //Coupon code validation
    $("#coupon_code").keyup(function(){
        var value = $(this).val();
        var data = {
          code:value,
          validateCouponCode:true
        }
        $.post("core.php",data,function(response){
            //Since the response will be json_encode'd JSON string we parse it here
            var callback = JSON.parse(response);
            if(callback.status){
                $("#couponStatus").html(" <span style='color:green'>Coupon is valid =) "+callback.discount_rate+"% discount</span> ");
            }else{
                $("#couponStatus").html(" <span style='color:red'>Coupon is not valid</span> ");
            }
        })
    })
    //Coupon Code validation END

}); // Document ready.

// Function handles the Stripe response:
function stripeResponseHandler(status, response) {

    // Check for an error:
    if (response.error) {

        reportError(response.error.message);

    } else { // No errors, submit the form:

        var f = $("#preorder");

        // Token contains id, last4, and card type:
        var token = response['id'];

        // Insert the token into the form so it gets submitted to the server
        f.append("<input type='hidden' name='stripeToken' value='" + token + "' />");

        // Submit the form:
        f.get(0).submit();

    }

} // End of stripeResponseHandler() function.

这是 core.php:

//For ajax requests create an empty respond object 
$respond = new stdClass();
$respond->status = false;
//END

$conn = mysql_connect("localhost",DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME);

//Execute the query
$foo = mysql_query("SELECT * FROM coupons WHERE expire > NOW() OR expire IS NULL OR expire = '0000-00-00 00:00:00'");
//Create an empty array
$rows = array();
while ($a=mysql_fetch_assoc($foo)) {
    //Assign the rows fetched from query to the array
    $rows[] = $a;
}
//Turn the array into an array of objects
$coupons = json_decode(json_encode($rows));

if(@$_POST["validateCouponCode"]){
    foreach ($coupons as $coupon) {
        if($coupon->coupon_code == $_POST["code"]){
            //Coupon found
                $respond->status = true;
                //Additional instances to the respond object
                $respond->discount_rate = $coupon->coupon_discount;
        }
    }
    echo json_encode($respond);
}

最佳答案

经过几个小时的练习,我最终找到了解决方案并且它正在发挥作用。

感谢大家的建议。 仍然愿意接受任何改进代码的建议。

// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {


// Stores errors:
$errors = array();

// Need a payment token:
if (isset($_POST['stripeToken'])) {

  $token = $_POST['stripeToken'];

  // Check for a duplicate submission, just in case:
  // Uses sessions, you could use a cookie instead.
  if (isset($_SESSION['token']) && ($_SESSION['token'] == $token)) {
    $errors['token'] = 'You have apparently resubmitted the form. Please do not do that.';
  } else { // New submission.
    $_SESSION['token'] = $token;
  }

} else {
  $errors['token'] = 'The order cannot be processed. Please make sure you have JavaScript enabled and try again.';
}

$unitCost       = 4995;
$intRate        = 1500;
$domRate        = 500;
//print_r($_POST);


$email          = $_POST['email'];
$qty            = $_POST['qty'];
$cardName       = $_POST['card-name'];
$cardAddress1   = $_POST['address'];
$cardAddress2   = $_POST['address2'];
$cardCity       = $_POST['city'];
$cardState      = $_POST['state'];
$cardZipcode    = $_POST['zipcode'];
$shippingMethod = $_POST['shipping-method'];
$product        = $_POST['kloqeColor'];
$token          = $_POST['stripeToken'];
$couponDiscount = '';

$sql = "SELECT * FROM `------`.`coupons` WHERE `coupon_code` = '" .addslashes($_POST['coupon-code']) . "'";

//echo $sql;
$query = $connectAdmin->Query($sql);


if($query->num_rows > 0) {

$results = $query->fetch_array(MYSQLI_ASSOC);

$couponDiscount = $results['coupon_discount'];
}

//echo '<pre>' . print_r($_POST, true) . '</pre>';
$amount = $unitCost;

if(!empty($couponDiscount)) {
//$amount = ($unitCost - $unitCost * $couponDiscount / 100);
//echo 'Discount not empty<br>';
$amount = $unitCost * ((100-$couponDiscount) / 100);
}

//echo $amount . '<br>';

关于javascript - undefined index 错误 - 如何设置折扣后的最后金额?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665672/

相关文章:

javascript - 用于移动设备的 Html 导航栏菜单

php - MySQL 将 PHP 中的 UTF-8 条目正确保存在 VARCHAR 中,但不能保存在文本 blob 中

php - 在 PHP 中获取图像对象的内容

angular - 是否可以通过更改监听器检索在表单控件中选择的选项的编号?

php - 在侧边栏中显示文件夹和子文件夹

javascript - 如何定位下一个 <div> 元素?

javascript - jQuery - 从 2 列表创建数组

javascript - 在javascript中合并两个文本

javascript - 在子状态更改时触发父组件更新

php - Wordpress 查询运行两次