I am trying to put Stripe into my web page to accept payments. But whenever I load the page I get an error saying that stripeCheckout is not defined. I know this has to do with the library imported in one of my script tags, but I am not sure why it is showing up as undefined. The library imported I thought was correct. Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- CSS Link -->
<link rel="stylesheet" href="styles.css">
<title>Store</title>
<script src="https://checkout.stripe.com/checkout.js" defer></script>
<script>
var stripePublicKey = '<%= stripePublicKey %>'
</script>
<script src="store.js" defer></script>
</head>
and this in my store.js file
const stripeHandler = stripeCheckout.configure({
key: stripePublicKey,
locale: 'auto',
token: function(token){
}
})
// Removes cart items after they are purchased
const purchaseItems = () => {
// let cartItems = document.getElementsByClassName('cart-items')[0]
// while(cartItems.hasChildNodes()){
// cartItems.removeChild(cartItems.firstChild)
// }
// updateCartTotal()
let priceElement = document.getElementsByClassName('cart-total-price')[0]
let price = parseFloat(priceElement.innerText.replace('$', '')) * 100
stripeHandler.open({
amount: price
})
}
I believe that that particular Stripe checkout API (and script) is now deprecated.
Here's a link to the docs for the new APIs: https://stripe.com/docs/payments/checkout/migration#client-products
Example from docs:
// client.html
<script src="https://js.stripe.com/v3"></script>
<button id="checkout-button">Pay</button>
// client.js
var stripe = Stripe('YOUR_API_KEY');
var checkoutButton = document.querySelector('#checkout-button');
checkoutButton.addEventListener('click', function () {
stripe.redirectToCheckout({
items: [{
// Define the product and SKU in the Dashboard first, and use the SKU
// ID in your client-side code.
sku: 'sku_123',
quantity: 1
}],
successUrl: 'https://www.example.com/success',
cancelUrl: 'https://www.example.com/cancel'
});
});
Related
So i am trying to get a first_name from JSON object which has array of elements by iterating through it, for example if i type 'Ron' it will display as a text but for some reason I can't get display it as a text unless i send in a respond this `
playerName: nbaPlayer[0]
But it only displays one element as a text since others are not in a response
reponse in a server enter image description here
Here is a code for fetch where i use search bar from handlebars to search for a first_name
const nbaForm = document.querySelector('form')
const search = document.querySelector('input')
const messageOne = document.querySelector('#player-1')
nbaForm.addEventListener('submit', (event) => {
event.preventDefault()
const playerSearch = search.value
messageOne.textContent = 'Loading...'
fetch('http://localhost:4000/nba').then((response) => {
response.json().then(nbaData => {
if (nbaData.playerName === playerSearch) {
messageOne.textContent = nbaData.playerName
} else {
messageOne.textContent = 'not found'
}
})
})
})
request method
app.get('/nba', (req,res) => {
networkManager.nbaPlayerData((data)=>{
/
var nbaPlayer = []
for(var i=0; i<data.data.length; i++){
nbaPlayer.push(data.data[i].first_name)
}
console.log(nbaPlayer)
res.send({
playerName: nbaPlayer
})
})
})
handlebars file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NBA</title>
<link rel = "stylesheet" href="/css/style.css">
</head>
<body>
<div class="main-content">
<h1>NBA SERVER</h1>
<p>Use this site to get NBA player</p>
<form action="">
<input placeholder="Type a players name">
<button>Search</button>
</form>
<p id="player-1"></p>
<h1>{{playerName}}</h1>
</div>
<script src ="/js/fetch-app.js"></script>
</body>
</html>
try this.
fetch('http://localhost:4000/nba').then((response) => {
response.json().then(nbaData => {
var index = nbaData.playerName.indexOf(playerSearch)
if (index !== -1) {
messageOne.textContent = nbaData.playerName[index]
} else {
messageOne.textContent = 'not found'
}
})
})
You are getting an array from
res.send({
playerName: nbaPlayer // nbaPlayer is array
})
but in your fetch, you want to get data as from simple object
So, I'm trying to pass some data to a chart (using chartjs and django) and I can print my data in my webpage, but can't pass it as arguments to the chart. Also, if I put data hardcoded in the chart it works, but with my own data from an array I can't see anything...
I've tried {{data | safe}} and {{labels | safe}} but I get an error, so I'm not getting what I'm doing wrong. Can anyone help me?
To explain better:
views.py
import csv
def home(request):
csvFilePath = "../data/raw_datasets/covid_confirmed.csv"
data = []
labels = []
with open(csvFilePath, "r") as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
next(csv_reader)
for row in csv_reader:
data.append(row[1])
labels.append(row[73])
return render(request, 'home.html',
{
'data': data,
'labels': labels
})
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<title>Crypto Covid</title>
</head>
<body>
<h4>{{data | safe}}</h4>
<p>--------------</p>
<h4>{{labels|safe}}</h4>
<div class="container">
<canvas id="chart">
</canvas>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<script> src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"</script>
<script>
var config = {
type: 'pie',
data: {
datasets: [{
data: {data} ,
backgroundColor: [
'#696969', '#808080', '#A9A9A9', '#C0C0C0', '#D3D3D3'
],
label: 'Population'
}],
labels: {labels}
},
options: {
responsive: true
}
};
window.onload = function() {
var ctx = document.getElementById('chart').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
</html>
The result in my page:
my result page
you need to use template tag called json_script, {{ your_array|json_script:"chart_data" }} and then access this data in javascript -
var value = JSON.parse(document.getElementById('chart_data').textContent);
https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#json-scriptDjango documentation
Try this please
import csv
def home(request):
csvFilePath = "../data/raw_datasets/covid_confirmed.csv"
data_list = []
with open(csvFilePath, "r") as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
next(csv_reader)
for row in csv_reader:
data_list.append({'label' : row[73], "y" : row[1]})
t = json.dumps(data_list)
return render(request, 'home.html',
{
'output':t
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<title>Crypto Covid</title>
</head>
<body>
<div id="pie-chart" style="width: 100%;height:370px;">
</div> <!-- edited -->
</body>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> <!-- edited--></script>
<!-- edited -->
data = JSON.parse("{{ output|escapejs }}")
window.onload = function() {
var chart = new CanvasJS.Chart("pie-chart", {
type: 'pie',
data: [{type: "pie",dataPoints: data}],
options: {
responsive: true
}
});
chart.render();
};
</script>
</html>
Try passing the data list by list (I use render_template on Flask) and retrieve it on javascript (as an array) with:
labels: [{% for item in families %}
"{{ item }}",
{% endfor %}]
...even if pylint may say criticize the html syntaxe. It runs well.
A third party sent me this script. Basically,
include a script
call the object
onAuthorize will feedback data, then do something with data
Is it a way to integrate it with react? I think I need the data from onAuthorize to update my react state
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<title>Payment Gateway Test Page</title>
<script src="https://service.com/widget.js">
</script>
<style type="text/css">
iframe{border: 0;height: 50px;}
</style>
</head>
<body>
<div>
* Demo for widget
</div>
<br/>
<script>
// widget
mywidget.Button.render({
Client: {
id: "1234",
name: "testme"
},
payment: function (actions) {
var amountValue = parseFloat(document.getElementById("inp-amount").innerText);
return actions.createQuote(amountValue)
},
onAuthorize: function (data) {
// err
if (data.errorCode) {
this.onError(data);
return;
}
// money we need to pay
var amountValue = parseFloat(document.getElementById("inp-amount").innerText);
// we have such points, converted to money
var pointsDollars = parseFloat(data.pointsBurned * 0.005, 10);
// points to convert
document.getElementById('qp').innerText = data.pointsBurned;
// origPay - new_money = pay_now
document.getElementById('bal').innerText = '$' + (amountValue - pointsDollars);
},
onError: function (data) {
console.log(data);
},
onClicked: function (data) {
// on click
console.log(data);
}
}, "#container"); // container
</script>
<div id="container"></div>
<br/>
<div id="amount">
Checkout: $<span id="inp-amount">1543</span> <br>
Points to redeem: <span id="qp"></span> <br>
<hr>
Balance to pay: <span id="bal"></span> <br>
</div>
</body>
</html>
You could create an event and listen for that event. In onAuthorize you can trigger the event and pass the data.
Add an event in your page (not necessarily in React)
// Create the event
var event = new CustomEvent("authroize-me", { "detail": "some event info" });
React component
constructor() {
super();
this.handleAuthroizeMe = this.handleAuthroizeMe.bind(this);
}
handleAuthroizeMe(data) {
console.log(data);
}
componentDidMount() {
document.addEventListener('authroize-me', this.handleAuthroizeMe);
}
componentWillUnmount() {
document.removeEventListener("authroize-me", this.handleAuthroizeMe);
}
In onAuthorize
onAuthorize: function (data) {
// Dispatch event
document.dispatchEvent(event, data);
}
Another quick and dirty fix.
Expose a function from react component outside the react scope.
window.setAuthorizeState = (data)=> {
this.setState({authorizeState: data});
}
Call setAuthorizeState from onAuthorize
The code can be embedded in a component which renders the container. And in componentDidMount, the script can be placed.
class Widget extends Component {
componentDidMount() {
// script here
}
render() {
return (
<div id="container" />
);
}
}
I am creating a simple rest api in javascript, I want upon initialization, the widget must display a list of all characters.
here is folder structure :
├───book
└───book.js
├───store
│ └───store.js
here is my store.js
window.Store = {
create: function() {
var self = {};
var props = {
name: 'string',
species: 'string',
picture: 'string',
description: 'string'
};
var listProps = ['name', 'species'];
var detailProps = ['name', 'species', 'picture', 'description'];
var characters = [
{
id: makeID(),
name: 'Ndiefi',
species: 'Wookie',
picture: 'store/img/ndiefi.png',
description: 'A legendary Wookiee warrior and Han Solo’s co-pilot aboard the Millennium Falcon, Chewbacca was part of a core group of Rebels who restored freedom to the galaxy. Known for his short temper and accuracy with a bowcaster, Chewie also has a big heart -- and is unwavering in his loyalty to his friends. He has stuck with Han through years of turmoil that have changed both the galaxy and their lives.',
_delay: 500
},
];
}
}
here is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Character Book</title>
<!-- 3rd party vendor libraries -->
<link rel="stylesheet" href="vendor/font-awesome-4.6.3/css/font-awesome.min.css">
<script src="vendor/jquery-3.1.0.min.js"></script>
<script src="vendor/underscore-1.8.3.min.js"></script>
<!-- 1st party internal libraries -->
<script src="store/store.js"></script>
<script src="tests/start-test.js"></script>
<script src="tests/test-book.js"></script>
<!-- The source of the 'Book' widget -->
<link href="book/book.css" rel="stylesheet">
<script src="book/book.js"></script>
<script>
$(function() {
var frame = $('#test-frame');
var run = $('#test-run');
var results = $('#test-results');
var store = Store.create();
run.click(function() {
run.prop('disabled', true).text('Running Tests');
results.removeClass('test-pass test-fail').text('');
testBook(frame).then(
function success() {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-pass').text('All tests passed');
},
function failure(err) {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-fail').text('Test failed, see console');
}
);
});
Book.init(frame, store);
});
</script>
</head>
<body>
<button id="test-run">Run Tests</button>
<span id="test-results"></span>
<div id="test-frame">
</div>
</body>
</html>
here is what I have tried :
books.js
var data = JSON.parse(characters);
data.forEach(characters => {
console.log(characters.name)
});
so when I run the app in my browser I see the following error :
Uncaught ReferenceError: characters is not defined
what is wrong with my code ? any suggestion or help will be helpfull thanks
Having issues integrating socket io + express js onto my Bluehost server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Poll App</title>
<link rel="stylesheet" href="/style.css">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container" id="react-container">
<h1>Live Polling</h1>
</div>
<!-- <script src="/socket.io-client/dist/socket.io.js"></script> -->
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script src="./dist/bundle.js"></script>
<!-- <script src="/socket.io/socket.io.js"></script> -->
</body>
</html>
here's my app.js
var React = require('react');
var Router = require('react-router');
var RouteHandler = Router.RouteHandler;
var Header = require('./parts/Header');
var io = require('socket.io-client');
var APP = React.createClass({
getInitialState(){
return {
status : 'disconnected',
title : '',
member : {},
audience: [],
speaker : '',
questions: [],
currentQuestion: false
}
},
componentWillMount(){
this.socket = io('react-test.derrickmv.com');
this.socket.on('connect', this.connect);
this.socket.on('disconnect', this.disconnect);
this.socket.on('welcome', this.updateState);
this.socket.on('joined', this.joined);
this.socket.on('audience', this.updateAudience);
this.socket.on('start', this.start);
this.socket.on('end', this.updateState);
this.socket.on('ask', this.ask);
},
emit(eventName, payload){
this.socket.emit(eventName, payload);
},
connect(){
var member = (sessionStorage.member) ? JSON.parse(sessionStorage.member): null;
if (member && member.type ==='audience'){
this.emit('join', member);
} else if (member && member.type === 'speaker'){
this.emit('start', {name: member.name, title : sessionStorage.title});
}
this.setState({ status: 'connected'});
},
disconnect(){
this.setState({
status: 'disconnected',
title: 'disconnected',
speaker: ''
});
},
updateState(serverState){
this.setState(serverState);
},
joined(member){
sessionStorage.member = JSON.stringify(member);
this.setState({ member: member});
},
start(presentation){
if( this.state.member.type === 'speaker'){
sessionStorage.title = presentation.title;
}
this.setState(presentation);
},
ask(question){
sessionStorage.answer = '';
this.setState({ currentQuestion: question });
},
updateAudience(newAudience){
this.setState({ audience: newAudience});
},
render(){
return (
<div>
<Header {...this.state} />
<RouteHandler emit={this.emit} {...this.state} />
</div>
);
}
});
module.exports = APP;
After placing everything into my server, I get the following errors in the console log stating a 404 (Not Found) Error.
Here's my app-server.js:
Thanks so much for helping!