How to add Paypal buy buttons to items in aspx page? - asp.net

I am a newbie to paypal. I got a sandbox test item onpaypal and created an
item Buy button which is embedded html code.
Now whenever I insert the html code in the aspx page, it dosen't redirect to the paypal site.
Maybe because of the form tag that covers the html code. Here is the code for paypal buy button for an item:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="3GWR6RV47BCVE">
<input type="image" src="https://www.paypalobjects.com/en_GB/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.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
I tried this code in a plain HTML file, and it worked. But as soon as I put it in a form runat server tag on aspx, it redirects the page to itself.

The problem is that ASP.NET pages define a form within which all the controls are placed (especially if you are using a master page) and HTML does not allow nested form tags.
There are several ways around this including using a normal ASP image button as described here.
You can also use an anchor link as described in this blog. However as noted by the author, the user can save the page source, edit it (e.g. change the price) and then reload it and click the link.
In fact any method that stores the information in the source of the webpage has potential to be abused. Therefore the approach I like, is to use a combination of an ASP image button and the anchor link approach but to implement this on the sever within the button click event:
1) In your ASP page define an image button where you want the PayPal button to go. You can set the ImageURL to the preferred button type provided by PayPal.
<asp:ImageButton
ID="PayPalBtn"
runat="server"
ImageUrl="https://www.paypalobjects.com/en_GB/i/btn/btn_buynow_LG.gif"
onclick="PayPalBtn_Click" />
2) Use the Click event of the button to generate the required information on the server side and then redirect the browser to the PayPal site.
protected void PayPalBtn_Click(object sender, ImageClickEventArgs e)
{
string business = "<insert your paypal email or merchant id here>";
string itemName = "<insert the item name here>";
double itemAmount = 123.451;
string currencyCode = "GBP";
StringBuilder ppHref = new StringBuilder();
ppHref.Append("https://www.paypal.com/cgi-bin/webscr?cmd=_xclick");
ppHref.Append("&business=" + business);
ppHref.Append("&item_name=" + itemName);
ppHref.Append("&amount=" + itemAmount.ToString("#.00"));
ppHref.Append("&currency_code=" + currencyCode);
Response.Redirect(ppHref.ToString(), true);
}
Disclaimer: It may still be possible for users to abuse this approach (although it is now a bit harder) so it is always best to check what has been paid before dispatching goods.

An ASPX page is like a giant HTML form. You need to close the ASPX form before the PayPal button code starts.
Like this:
<form name="default.aspx">
-- Page content
</form>
<!-- Close the form-->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
-- button code
You can also try creating the button as a URL and hyperlink to some text or an image on your site - you can still use the PayPal button image. When you're viewing the button code within PayPal there should be a tab above it labeled "E-mail". Click that and you'll get a URL - if you're creating buttons with a drop-down menu or text field you cannot turn the button into a URL.

This is a hack way of doing it, but before the paypal code enter a closing form tag (This will close the asp pages form) then remove the closing form tag from the paypal code and allow the end of .net page end form tag to close the paypals form..

I did it using an iframe for each button
<iframe height="27" marginheight="0" src="/PayPalButton.htm?button_id=ABCXYZSSSSS" frameborder="0" width="120" marginwidth="0" scrolling="no"></iframe>
Here is the code inside PayPalButton.htm
<html>
<head>
<title>PayPal</title>
<script type = "text/javascript">
// function to get url parameter
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
// function to get button ID from url
function payPalButtonCode() {
var code = '<input value="_s-xclick" type="hidden" name="cmd" /> <input value="';
code = code + getURLParameters('button_id');
code = code + '" type="hidden" name="hosted_button_id" /> '
document.write(code);
}
function payPalButtonQuantity() {
var button_quantity_low = getURLParameters('button_quantity_low');
var button_quantity_high = getURLParameters('button_quantity_high');
var button_quantity_unit = getURLParameters('button_quantity_unit');
var button_quantity_units = getURLParameters('button_quantity_units');
var code = '';
var i;
if (button_quantity_low != 'No Parameters Found')
{
code = '<select name="quantity">';
for ( i = button_quantity_low; i <= button_quantity_high; i++) {
if (i > 1) {
code = code + String.format('<option value="{0}">{0} {1}</option>', i, button_quantity_units);
}
else {
code = code + String.format('<option value="{0}">{0} {1}</option>', i, button_quantity_unit);
}
}
code = code + '</select>';
}
else
{
code = '';
}
document.write(code);
}
function payPalButtonType() {
var code = '<input alt="PayPal – The safer, easier way to pay online." src="';
var button_type = getURLParameters('button_type');
if (button_type=='buy_now'){
code = code + 'https://www.paypalobjects.com/en_GB/i/btn/btn_buynow_LG.gif" type="image" name="submit" />';
}
else
{
//code = code + 'https://www.paypalobjects.com/en_GB/i/btn/btn_subscribe_SM.gif" type="image" name="submit" />';
code = code + 'https://www.paypalobjects.com/en_GB/i/btn/btn_buynow_LG.gif" type="image" name="submit" />';
}
document.write(code);
}
String.format = function() {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
</script>
</head>
<body>
<form id="f1" method="post" action="https://www.paypal.com/cgi-bin/webscr" target="_top">
<script type="text/javascript">payPalButtonCode();</script>
<script type="text/javascript">payPalButtonQuantity();</script>
<script type="text/javascript">payPalButtonType();</script>
<img alt="" style="border: 0px solid;" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" />
</form>
</body>
</html>

For fixed-price buttons, there's a VERY easy, html-only workaround. Just copy the email-link provided by paypal, and create a very normal link using <a> ... </a>, which as content has the image that would normally appear in the <form> statement:
<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3GWR6RV47BCVE" target="_top">
<img src="https://www.paypalobjects.com/it_IT/IT/i/btn/btn_buynowCC_LG.gif" border="0" title="submit" alt="PayPal – The safer, easier way to pay online." />
</a>
I've been searching for a solution today, so even if this thread hasn't been active lately, maybe this can be useful to someone else who wants to avoid code-behind.

Related

Submit button replacement with image

I have a desktop website written in php.
I have a form that has a submit button in the form of an image displaying the word "next". When my users complete the form and click on it i want it to display the loading gif. I have placed the necessary coding (as i understand it ) to do this but it does not replace the next image with the loading gif. Can anyone pick up what i'm doing wrong.
relevant code section below.
<div class="bb"><input type="image" src="./img/next.png" alt=" Create
My Account " onclick="ButtonClicked()"/></div>
<div class="lb"><input type="image" src="./img/loading6.gif" alt="
loading button "/></div>
<BR>
<BR>
<BR>
</form>
</div>
<script type="text/javascript">
function ButtonClicked()
{
document.getElementById("bb").style.display = "none"; // to undisplay
document.getElementById("lb").style.display = ""; // to display
return true;
}
var FirstLoading = true;
function RestoreSubmitButton()
{
if( FirstLoading )
{
FirstLoading = false;
return;
}
document.getElementById("bb").style.display = ""; // to display
document.getElementById("lb").style.display = "none"; // to undisplay
}
// To disable restoring submit button, disable or delete next line.
//document.onfocus = RestoreSubmitButton;
</script>
You use class for getElementById replace class by 'id' that will work better.
Each id must be single, you cannot have many time the same id.
And use img tag rather input for picture.
And to conclude display = "" and display ="none" it's the same use display = 'block' or display = 'inline-block';
Because there are no "IDs" on your HTML. You have set class names as 'bb' and 'lb'. Replace those classes with id and it will work. So change the HTML as below.
<div id="bb"><input type="image" src="./img/next.png" alt=" Create
My Account " onclick="ButtonClicked()"/></div>
<div id="lb"><input type="image" src="./img/loading6.gif" alt="
loading button "/></div>
<BR>
<BR>
<BR>
</form>
</div>

Forward and pass data along in Asp.net

In Asp.net Entity Framework I need to forward to another page and pass some data processed by the second page along.
In PHP I could do something like
<!-- page1.php -->
<form action="page2.php" method="POST">
<input type="hidden" name="id" />
<input type="submit" value="Go to page 2" />
</form>
<!-- page2.php -->
<?php
echo $_POST['id'];
?>
How can this be implemented in Asp.net?
Edit: There is a simple solution using Javascript and jQuery.
<!-- on page 1 -->
$('input[type=submit]').on('click', function (e) {
// Forward to browsing page and pass id in URL
e.preventDefault();
var id= $('input[name=id]').val();
if ("" == id)
return;
window.location.href = "#Request.Url.OriginalString/page2?id=" + id;
});
<!-- on page 2 -->
alert("#Request.QueryString["id"]");
There are, at least, two options:
Session state, like this:
Putting data into Session (your first page)
Session["Id"] = HiddenFieldId.Value;
Getting data out of Session (your second page)
// First check to see if value is still in session cache
if(Session["Id"] != null)
{
int id = Convert.ToInt32(Session["Id"]);
}
Query string, like this:
Putting the value into the URL for the second page as a query string
http://YOUR_APP/Page2.aspx?id=7
Reading the query string in the second page
int id = Request.QueryString["id"]; // value will be 7 in this example
There's a lot of ways to do this, take a look at this link for some guidance.
HTML page:
<form method="post" action="Page2.aspx" id="form1" name="form1">
<input id="id" name="id" type="hidden" value='test' />
<input type="submit" value="click" />
</form>
Code in Page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string value = Request["id"];
}
MVC would look like...
#using (Html.BeginForm("page2", "controllername", FormMethod.Post))
{
#Html.Hidden(f => f.id)
<input type="submit" value="click" />
}
also, read through these MVC tutorials, you shouldn't blindly translate what you know in PHP to ASP.NET MVC, since you need to learn the MVC pattern too.
You can also use <form> with method="POST" in ASP.NET. And get value in code:
int id = int.Parse(Request.Form["id"]);

How to read checkbox/radio value in freemarker?

I'm working with share forms in alfresco and trying to read the values of ticked checkboxes and checked radio buttons form a form. I extended both the user creation and userprofile form with these input controls and so far I have been unsuccessful at reading the textual values of said controls. Below is a snippet of code:
<div class="row">
<span class="label"><input id="${el}-input-spokenEnglish" type="checkbox" name="spokenLanguages" value="${msg("label.anglais"!"")?html}" /> ${msg("label.anglais")}</span>
<span class="label"><input id="${el}-input-spokenSpanish" type="checkbox" name="spokenLanguages" value="${msg("label.espagnol"!"")?html}" /> ${msg("label.espagnol")}</span>
<span class="label"><input id="${el}-input-spokenGerman" type="checkbox" name="spokenLanguages" value="${msg("label.allemand"!"")?html}" /> ${msg("label.allemand")}</span>
<span class="label"><input id="${el}-input-spokenChinese" type="checkbox" name="spokenLanguages" value="${msg("label.chinois"!"")?html}" /> ${msg("label.chinois")}</span>
<br/>
<span class="label">${msg("label.otherLanguages")} : </span>
<span class="input"><input id="${el}-input-spokenLanguages" type="text" size="30" maxlength="256" value="" <#immutablefield field="spokenLanugages" /> /> </span>
</div>
unfortunately I get nothing so far from whatever is returned and would gladly appreciate some insight into this.fre
If you look at userprofile.get.html.ftl, you'll see the following snippet:
<script type="text/javascript">//<![CDATA[
var userProfile = new Alfresco.UserProfile("${args.htmlid}").setOptions(
{
This means it's triggering a client-side JS file from Alfresco, in this case profile.js (see the head file). So just adding some input fields isn't enough.
You need to extend the client-side JS file.
In the function onEditProfile it gets the Dom elements.
But that's just for showing the actual fiels 'after' it's saved.
In profile.js you'll see: form.setSubmitAsJSON(true); that you have a json object from which you can get your fields.
And in userprofile.post.json.ftl it does a loop on the user.properties:
for (var i=0; i<names.length(); i++)
{
var field = names.get(i);
// look and set simple text input values
var index = field.indexOf("-input-");
if (index != -1)
{
user.properties[field.substring(index + 7)] = json.get(field);
}
// apply person description content field
else if (field.indexOf("-text-biography") != -1)
{
user.properties["persondescription"] = json.get(field);
}
}
user.save();
This probably means that you haven't extended the contentmodel of the cm:person object with your new properties.

Load dynamic list of elements AFTER FINISHED loading of several form elements

I have...
a dynamic populated select box
several input boxes
a submit button
form fields are loaded initially using cookies
several dynamic populated divs
I want...
start loading the content of my DIVs after all FORM elements have been loaded completely (= filled with data, select boxes are populated)
Sample code:
<script type="text/javascript">
$(document).ready(function() {
// Populate <select>
var options ='';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + i + '">' + i + '</option>';
}
$("select#myid").html(options);
})
...
</script>
<form>
<select id="myselect></select>
<input id="mytext" type="text" value="" />
<input type="submit" value="Search" />
</form>
<% foreach( MyElement element in MyListing) { %>
<div>
<script type="text/javascript">
$(document).ready(function() {
DoSomething($(select#myid).val());
})
</script>
</div>
<% } %>
Any help is very appreciated.
Edited for the extra information:
jQuery(function($) { // note that this is equivalent to $(document).load()
// if we are here, then all your page and form elements have loaded.
// Populate <select> as per your code above
$('div').each(function(index) { // perhaps give them a class?
$(this).load(<<someURL>>);
// it's not clear from your question how you intend to get the
// dynamic content, ie: what url to use?
});
});

CSS Hidden DIV Form Submit

Using CSS, when a link is clicked it brings up a hidden DIV that contains a form. The user will then enter information and then submit the form. I'd like the hidden DIV to remain visible, and a 'success message' to be displayed after submission. Then the user will have the option of closing the DIV. I can't get it to work without reloading the page, which causes the DIV to become hidden again. Any ideas?
<body>
Click Me
<!--POPUP-->
<div id="hideshow" style="visibility:hidden;">
<div id="fade"></div>
<div class="popup_block">
<div class="popup">
<a href="javascript:hideDiv()">
<img src="images/icon_close.png" class="cntrl" title="Close" />
</a>
<h3>Remove Camper</h3>
<form method="post" onsubmit="email.php">
<p><input name="Name" type="text" /></p>
<p><input name="Submit" type="submit" value="submit" /></p>
</form>
<div id="status" style="display:none;">success</div>
</div>
</div>
</div>
<!--END POPUP-->
<script language=javascript type='text/javascript'>
function hideDiv() {
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById('hideshow').style.visibility = 'hidden';
}
else {
if (document.layers) { // Netscape 4
document.hideshow.visibility = 'hidden';
}
else { // IE 4
document.all.hideshow.style.visibility = 'hidden';
}
}
}
function showDiv() {
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById('hideshow').style.visibility = 'visible';
}
else {
if (document.layers) { // Netscape 4
document.hideshow.visibility = 'visible';
}
else { // IE 4
document.all.hideshow.style.visibility = 'visible';
}
}
}
</script>
</body>
Forms by default submit content by changing to the specified page in its 'action' attribute. You will need to build additional scripts to prevent it from doing that and submit the data using either AJAX or jQuery then process the result.
Or you could simply use whatever language you're programming in to set the default visibility for the division. If the form data exists, display it by default, otherwise hide it by default.
How about using an AJAX call to post the form instead of posting back the whole page?
Instead of using a "submit" type for your button, you can use a "button" type and use a script called by onclick which will use ajax to submit the form and do whatever is necessary.
This defeats slightly the meaning of a form, but works well. You might also want to think about using a javascript library like prototype or similar (jquery, etc) that gives you the functionality to create a get or post array of your form in order to make it easier.

Resources