Adding Discount code button to Paypal buy now button - javascript

I'm trying to add a discount code to the paypal button, The javascript works and says the discount code is valid but isn't taking the discount off the amount when you click the buy now button to pay.
Can anyone help me please
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<p>Please click on the link to pay</p>
<input type="hidden" name="cmd" value="_cart" />
<input type="hidden" name="upload" value="1" />
<input type="hidden" name="business" value="<?php echo C_OUR_EMAIL; ?>" />
<input type="hidden" name="first_name" value="<?php echo strfordisp($ofirstname); ?>" />
<input type="hidden" name="last_name" value="<?php echo strfordisp($olastname); ?>" />
<input type="hidden" name="address1" value="<?php echo strfordisp($theorder["oaddress"]); ?>" />
<input type="hidden" name="address2" value="<?php echo strfordisp($theorder["oaddress2"]); ?>" />
<input type="hidden" name="address3" value="<?php echo strfordisp($theorder["oaddress3"]); ?>" />
<input type="hidden" name="city" value="<?php echo strfordisp($theorder["otown"]); ?>">
<input type="hidden" name="zip" value="<?php echo strfordisp($theorder["opostcode"]); ?>" />
<?php
$orderdets = mysql_query("select * from c4d_orderitems where orderid='" . $_SESSION["db_order"] . "' and confirm");
$iloop = 1;
while ($orderrow = mysql_fetch_array($orderdets))
{
$itemdesc = $orderrow["itemtypedesc"];
$itemdesc .= " to " . $orderrow["dpostcode"];
$itemprice = $orderrow["cost"] + $orderrow["surcharge"] + $orderrow["insurancecost"];
?>
<input type='hidden' name="item_name_<?php echo $iloop; ?>" value='<?php echo strfordisp($itemdesc); ?>' />
<input type='hidden' name="item_number_<?php echo $iloop; ?>" value='<?php echo $orderrow["itemtype"]; ?>' />
<input type='hidden' name="amount_<?php echo $iloop; ?>" value='<?php
if ((strtoupper($ofirstname)=="PCTRENDSTEST") || (strtoupper($olastname)=="PCTRENDSTEST") || (substr($_SERVER['REMOTE_ADDR'],0,11)=="82.152.55.1"))
echo("0.01");
else echo $itemprice;
?>' />
<input type='hidden' name="baseamt_<?php echo $iloop; ?>" value='<?php if ((strtoupper($ofirstname)=="PCTRENDSTEST") || (strtoupper($olastname)=="PCTRENDSTEST") || (substr($_SERVER['REMOTE_ADDR'],0,11)=="82.152.55.1"))
echo("0.01");
else echo $itemprice;
?>' />
<input type="hidden" name="basedes_<?php echo $iloop; ?>" value="" />
<input type='hidden' name="quantity_<?php echo $iloop; ?>" value='1' />
<?
$iloop++;
}
?>
<input type="hidden" name="return" value="<?php echo C_SITE_ROOT; ?>stage7.php" />
<meta http-equiv="return" content="3;url=stage7.php" />
<input type="hidden" name="cancel-return" value="<?php echo C_SITE_ROOT; ?>order-cancel.php" />
<input type="hidden" name="notify_url" value="<?php echo C_SITE_ROOT; ?>paypal.php" />
<input type="hidden" name="rm" value="2" />
<input type="hidden" name="invoice" value="<?php echo $_SESSION["db_order"]; ?>" />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="no-shipping" value="1" />
<input type="hidden" name="button_subtype" value="products" />
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest" />
<input type="hidden" name="country" value="GB" />
Enter Coupon code
<input type="text" size="10" name="coupcode"; />
<input type="button" value="Check code" onclick="coupval =this.form.coupcode.value; ChkCoup();" />
<p class='fmenu'><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"></p>
</form>
The javascript is:
var discnt = 0; // no default percent discount
var coupons = new Array ( // place to put coupon codes
"coup1", // 1st coupon value - comma seperated
"coup2", // 2nd coupon value - add all you want
"coup3" // 3rd coupon value
);
var coupdc = new Array ( 5,10,15
// place to put discounts for coupon vals
);
var coupval = "(blanket)"; // what user entered as coupon code
function ChkCoup () { // check user coupon entry
var i;
discnt = 0; // assume the worst
for (i=0; i<coupons.length; i++) {
if (coupval == coupons[i]) {
discnt = coupdc[i]; // remember the discount amt
alert ("This is a valid promo code! \n\n" + discnt + "%" +" discount now in effect.");
return;
}
}
alert ("'" + coupval + "' is not a valid promo code!");
}
function Pound (val) { // force to valid Pound amount
var str,pos,rnd=0;
if (val < .995) rnd = 1; // for old Netscape browsers
str = escape (val*1.0 + 0.005001 + rnd); // float, round, escape
pos = str.indexOf (".");
if (pos > 0) str = str.substring (rnd, pos + 3);
return str;
}
function ReadForm (obj1) { // apply the discount
var amt,des;
amt = obj1.amount_<?php echo $iloop; ?>.value*1.0; // base amount
des = obj1.basedes_<?php echo $iloop; ?>.value; // base description
if (discnt > 0) { // only if discount is active
amt = Pound (amt - (amt * discnt/100.0));
des = des + ", " + discnt + "%" + "dis, COUP = " + coupval;
}
obj1.amount.value = Pound (amt);
obj1.item_name.value = des;
}

Related

Saving form data into dynamic form when hitting back or refreshing page

Right now I have code to dynamically add input fields to my form. I want to be able to submit the data and go to the next page but if someone decides to go back, the newly made input fields would still be there with the data. The way I have it set up now is to echo onto the input fields which works with the first two but not the third.
When I hit back, I get this:
Here is my code:
<h2>Enter Beneficiaries for Tangible Personal Property:</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="input_fields_container">
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" ></input></td>
</tr>
</table>
</div>
<p style="color:red;"></p>
<h3>Enter Contingent Beneficiary: </h3>
Name:<input type="text" name="conben" value="<?php echo $_SESSION['conben'];?>" >
<br><br>
<button type="button" name="back" value="back" onclick="location.href='county.php'">Back</button>
<input type="submit" name="submitform" value="Next"></input>
<button type="button" name="download" onclick="location.href='downloadAdd.php'">Download will</button>
</form>
<script>
//script to add/remove fields
$(document).ready(function () {
var getControl=getCookie("countControls1");
var max_fields_limit = 2; // Set limit for maximum input fields
var x = 0; // Initialize counter for text box
for(var i=1; i<=getControl; i++) {
console.log(i);
addControls();
}
$('.add_more_button').click(function (e) { // Click event to add more fields
addControls();
});
function addControls()
{
console.log(x);
if (x < max_fields_limit ) {
x++; // Increment counter
setCookie("countControls1",x,100);
$('.input_fields_container').append('<div><tr id="row'+x+'"><td> Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['1'];?>" class="form-control name_list" /></td><td>&nbspPercentage of tangible personal property:<input type="number" min="0" max="100" style="width: 40px" name="percent[]" value="<?php echo $_SESSION['percent']['1'];?>" class="form-control name_list" /></td><td>Remove</td></tr>');; // Add input field
}
else if (x==2){
$("p").text("*Only 3 tangible beneficiaries are allowed.");
}
}
$('.input_fields_container').on("click", ".remove_field", function (e) { // User click on remove text links
$(this).parent('div').remove();
x--;
$("p").text("");
setCookie("countControls1",x,100);
});
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
$("#div1").html("Add cookie = ",getCookie(cname));
}
function getCookie(cname)
{
console.clear();
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
//console.log(cname);
//console.log(decodedCookie);
console.log(ca);
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
console.log(c.substring(name.length, c.length));
return (c.substring(name.length, c.length));
}
}
return "";
}
});
</script>
Is there anyway to achieve this in this way or do I need to implement something else?
You can just write the fields back using a loop because presumably you have the two arrays in your session. You should also use empty() or isset() to check if the session arrays exist first otherwise you will end up with warnings about undefined keys and such:
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" /></td>
</tr>
<?php
# Remove the first keys since you already used them above
unset($_SESSION['percent'][0],$_SESSION['ben'][0]);
# Just do a normal loop to create any remaining values
foreach($_SESSION['percent'] as $key => $value): ?>
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben'][$key];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $value; ?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
</tr>
<?php endforeach ?>

Error in cropping function in php

It's my full code for cropping image function.Its works.But it crops wrongly. I can't able to find out the mistake.Functionally work,but wrongly. My cropped photo
<img style="padding-top:5%;" src="<?php echo $rowquerycat2[KEY_NAME]; ?>" id="rrr" alt="" class="img-responsive" /></div>
<form style="display: none;" id="croptype">
<input type="text" id="x" name="x" />
<input type="text" id="y" name="y" />
<input type="text" id="w" name="w" />
<input type="text" id="h" name="h" />
<input type="button" value="Crop Image" id="crop_btn" onclick="crop_photo()" />
</form>
<div id="photo_container"> </div>
javascript code for passing the co-ordinates values through ajax function
function crop_photo() {
//alert("hi");
var x_ = $('#x').val();
var y_ = $('#y').val();
var w_ = $('#w').val();
var h_ = $('#h').val();
$.ajax({
url: 'crop_photo.php',
type: 'POST',
data: {x:x_, y:y_, w:w_, h:h_, targ_w:TARGET_W, targ_h:TARGET_H},
success:function(data){
alert("sucess");
$('#photo_container').html(data);
}
});
}
crop_photo.php.
<?php
$targ_w = $_POST['w'];
$targ_h = $_POST['h'];
$jpeg_quality = 90;
$src = $_POST['photo_url'];
$src1 = basename($src);
$ext = pathinfo($src1, PATHINFO_EXTENSION);
if($ext == 'jpg'){
$imagesrori = imagecreatefromjpeg($src);
}
//$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$imagesrori,0,0,$_POST['x'],$_POST['y'], $targ_w,$targ_h,$_POST['w'],$_POST['h']);
// create the physical photo
imagejpeg($dst_r, 'cropimage/' . $src1);
echo '<img src="'.'cropimage/'. $src1.'?'.time().'">';
exit;
?>

Validation for textfield to restrict for 6 digits

we need to set validation in textfield : "zip code" under checkout process in magento site.
i need to restrict this textfield for maximum 6 digits.
i am using following code for this :
<input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>"
name="billing[postcode]" id="billing:postcode"
value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>"
class="input-text validate-zip-international
<?php echo $this->helper('customer/address')->getAttributeValidationClass('postcode') ?>" placeholder="Postal code"/>
please help me to give validation for Restricting only for 6 digits
try this
function limit(element)
{
var max_chars = 6;
if(element.value.length > max_chars) {
element.value = element.value.substr(0, max_chars);
}
}
<input type="text" onkeydown="limit(this);" onkeyup="limit(this); "title="<?php echo $this->__('Zip/Postal Code') ?>"
name="billing[postcode]" id="billing:postcode"
value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>"
class="input-text validate-zip-international
<?php echo $this->helper('customer/address')->getAttributeValidationClass('postcode') ?>" placeholder="Postal code"/>
The better way is use the pattern attribute:
<input type="number" maxlength="6" pattern="[0-9]{6,}" placeholder="Zip code" required>
This is an example for validating phone number of 10 digits:
Html :
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
Script file:
<script>
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>

get the product automatically from dynamic textbox using javascript

I'd been searching for 2 days now and i cant find the solution for my problem.
I wanted to automatically multiplied two numbers from dynamically generated textbox with the use of PHP coming from mysql
FROM THIS
<input name="qty<?php echo $x ?>" type="text" id="qty<?php echo $x ?>" size="6" maxlength="10" onfocus="startCalc();" onblur="stopCalc();">
<td><label>
<input name="unit<?php echo $x ?>" type="text" id="unit<?php echo $x ?>" size="9" maxlength="12" onfocus="startCalc();" onblur="stopCalc();">
</label></td>
<td><input name="total<?php echo $x ?>" type="text" id="total<?php echo $x ?>" size="9" maxlength="12" style="background-color:#FFCC33" readonly></td>
</tr>
heres my javascript
function startCalc(){
interval = setInterval("Unit()",1);
}
function Unit()
{
var cost = document.getElementsByName('unit');
for(var i=1; i<cost.length; i++)
{
unit[i] = document.getElementById('unit' + i).value;
srr_qty[i]= document.getElementById('qty' + i).value;
total[i]=(unit[i] * 1)*(qty[i]* 1);
document.getElementById('srr_total'+ i).value = total[i];
totalAmount[i]=document.getElementById('total' + i).value;
return (totalAmount[i])
}
}
function stopCalc(){
clearInterval(interval);
}
Hope you can understand what i wanted to do.. thanks and hoping for your quick response :)
set the value attribute for input tags <input type="text" value="<something here>" />

Calculating checkbox totals with jQuery

I am trying to create a page total based on options selected from checkboxes.
here is my HTML markup:
<input type="checkbox" id="option1" name="option1" value="<?= $add[0] ?>" />t1 + £<?= $add[0] ?><br />
<input type="checkbox" id="option2" name="option2" value="<?= $add[1] ?>" /t2 + £<?= $add[1] ?><br />
<input type="checkbox" id="option3" name="option3" value="<?= $add[2] ?>" />t3 + £<?= $add[2] ?><br />
<input type="checkbox" id="option4" name="option4" value="<?= $add[3] ?>" />t4 + £<?= $add[3] ?> <br />
This is my JavaScript that doesn't work:
var option1 = 0;
var option2 = 0;
var option3 = 0;
var option4 = 0;
var op = 0;
var extra = document.getElementById('extra');
$(":input").change(function()
{
option1 = $("input[name=option1]:checked").attr("value");
option2 = $("input[name=option2]:checked").attr("value");
option3 = $("input[name=option3]:checked").attr("value");
option4 = $("input[name=option4]:checked").attr("value");
op = parseInt(option1) + parseInt(option2) + parseInt(option3) + parseInt(option4) ;
extra.innerHTML = '<p>£'+op+'</p>';
});
Have I gone wrong somewhere?
I have other totals working, have removed from script so it's easier to read, just this one doesn't work!
EDITED:
<input id="option1" name="option1" value="20" type="checkbox">t1 + £20<br>
<input id="option2" name="option2" value="20" type="checkbox">t2 + £20<br>
<input id="option3" name="option3" value="20" type="checkbox">t3 + £20<br>
<input id="option4" name="option4" value="20" type="checkbox">t4 + £20 <br>
ADDED RADIO:
<input id="delivery" name="delivery" value="0" checked="checked" type="radio"> Standard (72hrs) - no addtional charges<br>
<input id="delivery" name="delivery" value="200" type="radio"> 45hrs - £200 per email templates<br>
<input id="delivery" name="delivery" value="250" type="radio"> 24hrs - £250 per email templates<br>
It would be easiest if you could select all your checkboxes together (and be sure you're not grabbing other checkboxes you don't want to grab:
<div id="checkSet">
<input type="checkbox" id="option1" name="option1" value="<?= $add[0] ?>" />t1 + £<?= $add[0] ?><br />
<input type="checkbox" id="option2" name="option2" value="<?= $add[1] ?>" /t2 + £<?= $add[1] ?><br />
<input type="checkbox" id="option3" name="option3" value="<?= $add[2] ?>" />t3 + £<?= $add[2] ?><br />
<input type="checkbox" id="option4" name="option4" value="<?= $add[3] ?>" />t4 + £<?= $add[3] ?> <br />
</div>
then select all of them, and iterate over them, summing their values:
var sum = 0;
$('#checkSet :checked').each(function(){
sum += parseInt($(this).val(), '10');
});
There is an error in your html:
<input type="checkbox" id="option2" name="option2" value="<?= $add[1] ?>" />t2 + £<?= $add[1] ?><br />
Then when you do parseInt it's always better to specify the base you are parsing:
parseInt(option1, '10')
Otherwise you might have odd problems with values like 09.
Can I see the generated HTML output? Maybe one of the values of the checkboxes is not a number and can't be parsed.
Parsing it returns NaN and this gives you a problem when you add up the values.
I used this code and works but of course could be written much better
var extra = document.getElementById('extra');
$(":input").change(function()
{
var option1;
var option2;
var option3;
var option4;
var op = 0;
option1 = $("input[name=option1]:checked").attr("value");
option2 = $("input[name=option2]:checked").attr("value");
option3 = $("input[name=option3]:checked").attr("value");
option4 = $("input[name=option4]:checked").attr("value");
if (option1){
op += parseInt(option1, '10');
}
if (option2){
op += parseInt(option2, '10');
}
if (option3){
op += parseInt(option3, '10');
}
if (option4){
op += parseInt(option4, '10');
}
if (op > 0){
extra.innerHTML = '<p>£'+op+'</p>';
}else{
extra.innerHTML = '';
}
});
Look at the fiddle here

Categories

Resources