Ekn Ekn - 6 months ago 23
JSON Question

Undefined index errors - How do I set the last amount after discount?

I made a coupon code system for the admin to create new coupons. On the form, I need to calculate the last amount to be paid after the discount. I wrote the

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


before adding the shipping costs and processing the payment. I'm not sure if it's correct...

I'm getting undefined index errors for $email - $qty - $cardName - $cardAddress1 - $cardAddress2 - $cardCity - $cardState - $cardZipcode - $shippingMethod - $product - $token - $couponDiscount, weird but not for $unitCost, $intRate or $domRate.

How can I fix this?

This is my form 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 = "";


The form submission is done along with the coupon validation inside preorder.js, which is working well and checking the code correctly :

// 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.


Here is the 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);
}

Ekn Ekn
Answer

After hours of practice on this, I ended up finding the solution and it's working.

Thanks for everyone for their suggestions. Still open to any kind of advice to improve the code.

// 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>';
Comments