Displaying a JS var across different pages - javascript

This is a kind of difficult question because I'm not sure how to word it. I'm making a shopping cart website using HTML5 and JS and I've got most of it down, but need help with one important aspect.
At the moment my "Buy Now" buttons are in tags that link to 1 page where the user can enter his info and make the purchase, this page is called "checkout". I want this "checkout" page to display the price of the item he wishes to purchase.
For ex) The user clicks on an book worth $10.00 and clicks the buy now button. This button will send him to the confirmation page where it will show a fill form, but the page does not show the price of the item he is purchasing.
This is where my problem lies. I can't think of any solution for this besides making a different page for each product (I only have 9 products).
Also, if it isn't blatantly obvious, I'm still a beginner with JS. Any help would be appreciated in helping me figure out how to display the price on the "checkout" page of each specific item without creating 9 separate pages. Thank You.

If I understand correctly, you are asking how to store a variable in Javascript that can be retrieved by multiple pages.
The canonical way to do this is to use cookies. The native cookie library is rather messy, so I recommend using a cookie library, like this.
However, since your question is tagged html5, you might be open to the sessionStorage HTML5 solution for this, which is much simpler than cookies.
sessionStorage.setItem("price", 100);
var price = sessionStorage.getItem("price");

The best way is to use some serverside solution. The client sends his form to your server, where the form gets evaluated and an according html-page is rendered.
The only other way is either using cookies or local Storage - but that's rather ugly.
You definitely should read some tutorials about php and mysql, but I'll give you rough overview on how to achieve this.
You provide a form on your page like this:
<form method="post" action="your-serverside-phpscript-that-processes-your-form.php>
How many Ipads you wanna buy:<input type="number" name="ipads">
<button type="submit">
</form>
now on serverside your php-script can evaluate the form.
all formfields are stored in a $_POST array. ( $_POST["ipads"] ) gets the value the user entered in the form. You don't need to store these values in the database yet.
You evaluate the formvalues and create the checkout-page with the according data (total price). Now the user submits the checkout-form, which you again process and store in the database.
I won't write down (sry, too tired) how this serverside part works, there are tons of tuts out there, just search google for php+mysql.

Since you're wanting to persist this data all on the client-end, I would encourage you to check out Amplify.Store. In full disclosure, I am currently employed by the company behind it - but it's great, and free.
Saving data is easy:
amplify.store( 'cart', { name: 'Book Title', price: 10.99 } );
To access this a little later, you can simply call:
amplify.store( 'cart' );
This will return your object from which you can get all of the products currently loaded. Amplify will evaluate your system and determine which storage method is best, and use it. This removes all of the guess-work form your plate, and let's you just do what it is you're wanting to do.
Please understand that while it is convenient to persist data client-side, it is by no means secure. When dealing with transactions and issues of a financial nature, you should always keep figures out of the hands of the consumer.
Generally data like this is stored server-side, within a session, a database, or a combination of both. However, if you understand the risks, and your model permits this type of persistence, then by all means feel free to use this as a solution.

Related

Django - Dynamic number of ModelForms based on dropdown value

I have a form that registers teams of people. Based on a dropdown to select the number of members in the team, the form should show that many model forms, one for each member.
I am not particularly sure what the correct design patter for this is. Here are the solutions that I have come up with:
Use JS to generate the HTML for each member form and then use the Django ModelForm backend to parse each form. However, in this case I cannot use the inbuilt rendering functions of Django and validation notification becomes bothersome.
Send a GET request whenever the user changes the dropdown value, and the GET request specifies the number of members you want to add. But here it would result in any previously entered data being cleared.
Send a POST request via JS whenever the dropdown is updated, and then re-render the form with the appropriate values picked up from the POST request. I am not sure if this is the right way to do this and seems to be easy to get wrong.
Can you please advise on what is the best solution for this scenario?
I am pretty sure this has already been answered somewhere, but I can't seem to find it anywhere. If you have the link to the answer, please go ahead and mark this question as a duplicate.

Dynamic encrypted paypal button?

so I am creating a website that needs to have a subscribe PayPal button. I am currently using the paypal button js, but it is very insecure, and people can change the amount they pay. So I am going to need to use the encrypted button, but I am not sure how to achieve this and still be able to change the price depending on the user. The reason I need to do this is so the user will be able to select different amounts of something. Say they can select anywhere from 1 to 50 points that would alter the price so if 1 point is 1 dollar and the user select 24 the subscribe button amount will have to be 24 dollars a month. Below is the current code for creating a non encrypted button. As a side question if anyone happens to know if it is important to keep your merchant id a secret. If so how would I do this?
$("#paypal-button").html(
'<script src="js/paypal-button.min.js?merchant=[Merchant ID]"' +
'data-button="subscribe"' +
'data-name="Custom Howloop Subscription"' +
'data-amount="' + roundTotal + '"' +
'data-recurrence="1"' +
'data-period="M"' +
'async' +
'> </script>'
);
A long time ago I tried to do something similar to this.
To my knowledge, there is no way to do it. You won't be able to simply change the values of the encrypted button and if it isn't encrypted, the user can change it and basically pay anything.
If you want to be able to safely and dynamically change values, I would suggest looking into their API/Express Checkout. That's what I did, and I am really glad that I did.
You can check everything before it is forwarded to PayPal, and I have never had an issue with that aspect of it (I pass the item ID and query my database to get the cost/etc and apply other checks to stop various issues.). And you can go through and apply any calculations that you need to for the price without an issue.
Otherwise, the only way I could think of is having multiple encrypted buttons for different prices. But that isn't very fun nor an optimal solution.
Edit: Now that I am not on mobile, here is a link to the Express Checkout Getting Started Guide.
Also, I do not believe that you need to worry about your Merchant ID being seen. It is used to process payments and I believe it can be seen in the transaction details.
YES THERE IS A WAY! Dont listen to the nay-sayers, i have recently successfully implemented encryption on dynamically created shopping cart information which was being injected into a empty form using php. I'm really planning to create a full tutorial because it seems that this information is RARE (i wonder why Paypal doesn't have a standard tutorial for this). I remember having days of stress because of this problem and almost a month later i happened to stumble on a tutorial provided here: https://www.stellarwebsolutions.com/en/articles/paypal_button_encryption_php.php
After some minor modifications i was able to use the PHP code to encrypt the data using my generated private keys and public certificates (make sure u have HTTPS on your website). Paypal was then able to successfully decrypt the information! (Oh boy you bet i did the happy dance)
Making sure data is valid only using IPN after payment is made is a very messy approach when u can avoid most tampering by doing custom encryption. Anyways until i buckle down and create a video tutorial good luck with the endeavor - on looking back i see how truly simple this process really is!
There's no way to do this without hosting the button details on PayPal's side. This would also happen in an old-style PayPal form integration where anyone can go into Chrome's Devtools and alter html form variables for example. As a workaround, you can implement one hosted subscribe button and have users change the quantity of the subscription. If your prices scale linearly with quantity of points then it'll work.

Update html 'permanenlty' with no database?

I made a website for crowd-funding. I know that we should have used a platform for this. (other issues determined us not to)
The page that I have created has no database behind.
What I am trying to do is create some kind of hidden form that updates the sum that was raised so far.
I am not a very technical person but I do know that modifications made through javascript / jQuery ar usually temporary.
But, since scripts like website visit counters do exist I am wondering and appealing to the collective wisdom of this community:
Is there a way to update an attribute of a html element through some kind of hidden form without a database behind?
Perhaps writing to a .json file and updating the attribute from the data?
(I need to do this today as I will not be at the office during the campaign and it is very hard for a person that has no technical skills to do it... not that hard, but still, not user friendly.)
In order to display variable data, you need to get these data somewhere.
Do you have write access to your server file system?
What service level do you expect during data manipulation? Does it suffice if you just go and upload modified file every time manually?
What about embed in your Web page an IMG and then upload it with always the same name and different content?
There is a database even behind "dummy" hit counters, no magic.

which is better, searching in javascript or database?

I have a grid(employee grid) which has say 1000-2000 rows.
I display employee name and department in the grid.
When I get data for the grid, I get other detail for the employee too(Date of Birth, location,role,etc)
So the user has option to edit the employee details. when he clicks edit, I need to display other employee details in the pop up. since I have stored all the data in JavaScript, I search for the particular id and display all the details. so the code will be like
function getUserDetails(employeeId){
//i store all the employeedetails in a variable employeeInformation while getting //data for the grid.
for(var i=0;i<employeeInformation.length;i++){
if(employeeInformation[i].employeeID==employeeId){
//display employee details.
}
}
}
the second solution will be like pass employeeid to the database and get all the information for the employee. The code will be like
function getUserDetails(employeeId){
//make an ajax call to the controller which will call a procedure in the database
// to get the employee details
//then display employee details
}
So, which solution do you think will be optimal when I am handling 1000-2000 records.
I don't want to make the JavaScript heavy by storing a lot of data in the page.
UPDATED:
so one of my friend came up with a simple solution.
I am storing 4 columns for 500 rows(average). So I don't think there should not be rapid slowness in the webpage.
while loading the rows to the grid, under edit link, I give the data-rowId as an attribute so that it will be easy to retrieve the data.
say I store all the employee information in a variable called employeeInfo.
when someone clicks the edit link.. $(this).attr('data-rowId') will give the rowId and employeeInfo[$(this).attr('data-rowId')] should give all the information about the employee.
instead of storing the employeeid and looping over the employee table to find the matching employeeid, the rowid should do the trick. this is very simple. but did not strike me.
I would suggest you make an AJAX call to the controller. Because of two main reasons
It is not advisable to handle Database actiity in javascript due to security issues.
Javascript runs on client side machine it should have the least load and computation.
Javascript should be as light as possible. So i suggest you do it in the database itself.
Don't count on JavaScript performance, because it is heavily depend on computer that is running on. I suggest you to store and search on server-side rather than loading heavy payload of data in Browser which is quite restricted to resources of end-user.
Running long loops in JavaScript can lead to an unresponsive and irritating UI. Use Ajax calls to get needed data as a good practice.
Are you using HTML5? Will your users typically have relatively fast multicore computers? If so, a web-worker (http://www.w3schools.com/html/html5_webworkers.asp) might be a way to offload the search to the client while maintaining UI responsiveness.
Note, I've never used a Worker, so this advice may be way off base, but they certainly look interesting for something like this.
In terms of separation of concerns, and recommended best approach, you should be handling that domain-level data retrieval on your server, and relying on the client-side for processing and displaying only the records with which it is concerned.
By populating your client with several thousand records for it to then parse, sort, search, etc., you not only take a huge performance hit and diminish user experience, but you also create many potential security risks. Obviously this also depends on the nature of the data in the application, but for something such as employee records, you probably don't want to be storing that on the client-side. Anyone using the application will then have access to all of that.
The more pragmatic approach to this problem is to have your controller populate the client with only the specific data which pertains to it, eliminating the need for searching through many records. You can also retrieve a single object by making an ajax query to your server to retrieve the data. This has the dual benefit of guaranteeing that you're displaying the current state of the DB, as well as being far more optimized than anything you could ever hope to write in JS.

Exposing server-side state through client-side controls in ASP.net

Hopefully this isn't a redundant question--I'm not really sure how to word it. Let's say I have a list of items on an ASP.net page. That list is selectable in that whenever the user clicks on one, the page does a postback and the server code stores the index or some unique identifier of the picture in a ViewState property indicating that it is currently selected.
I would like to minimize the load on the server and therefore I would like to store the index or unique identifier representing the image in some way on the client side. The best way I can think to do this is to store said information in a hidden field ), however I had two questions about this before I go crazy:
Is this a security risk in any way, shape or form (i.e., exposing implementation details of the page)?
Is there a better/best way to do this that is more industry-standard? Does ASP.net provide a framework to do this that is cleaner than my idea? Seems like this would be a fairly common requirement to me...
I have been working in ASP.net for about two years now. Please, be kind :-)
Best,
Patrick Kozub
The only security risk would be if some list items must remain non-selectable. It sounds like that is not the case in your situation. The user already knows the information, because he or she already selected the item.
NOTE: If the server ever does anything with that information and pulls it back from the user, then you must validate the index value. Otherwise, the user could change it to an invalid index, such as (-2), and trigger an exception.
You can store the index (or related value) in a global javascript variable. If you're avoiding a trip back to the server, .NET doesn't really have a role to play.

Categories