Google charts with Fusion Table Example error - google-visualization

Alright so I copy and pasted this example from google's chart tools documentation:
https://developers.google.com/fusiontables/docs/samples/gviz_datatable
I simply replaced their fusion table info with mine and am unable to get the table to appear.
This is what I have now with the fusion table set to public access:
<html>
<head>
<meta charset="UTF-8">
<title>Fusion Tables API Example: Google Chart Tools Data Table</title>
<link href="/apis/fusiontables/docs/samples/style/default.css"
rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['table'] });
function drawTable() {
var query = "SELECT 'fundraiser' as fundraiser, " +
"'price' as price, 'merchant' as merchant " +
'FROM 1QN6e86FybBULPekKvvXd_RF1jw01H7bZAJFjhUg';
var fundraiser = document.getElementById('fundraiser').value;
if (team) {
query += " WHERE 'fundraiser' = '" + fundraiser + "'";
}
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
gvizQuery.send(function(response) {
var table = new google.visualization.Table(
document.getElementById('visualization'));
table.draw(response.getDataTable(), {
showRowNumber: true
});
});
}
google.setOnLoadCallback(drawTable);
</script>
</head>
<body>
<div>
<label>Scoring Team:</label>
<select id="fundraiser" onchange="drawTable();">
<option value="">All</option>
<option value="default">default</option>
<option value="aaaatester">aaaatester</option>
</select>
</div>
<div id="visualization"></div>
</body>
</html>

I'm not sure what exactly was wrong with your query, but this works for me:
function drawTable () {
console.log('foo');
var query = 'SELECT fundraiser, price, merchant FROM 1QN6e86FybBULPekKvvXd_RF1jw01H7bZAJFjhUg';
var fundraiser = document.getElementById('fundraiser').value;
if (fundraiser) {
query += ' WHERE fundraiser = \'' + fundraiser + '\'';
}
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
gvizQuery.send(function(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var table = new google.visualization.Table(document.getElementById('visualization'));
table.draw(response.getDataTable(), {
showRowNumber: true
});
});
}
function init () {
// draw the table
drawTable();
// setup the fundraiser dropdown to redraw the table when the user changes the value
var el = document.querySelector('#fundraiser');
if (document.addEventListener) {
el.addEventListener('change', drawTable);
}
else if (document.attachEvent) {
el.attachEvent('onchange', drawTable);
}
else {
el.onchange = drawTable;
}
}
google.load('visualization', '1', {packages: ['table'], callback: init});
With this as the HTML:
<div>
<label>Scoring Team:</label>
<select id="fundraiser">
<option value="">All</option>
<option value="default">default</option>
<option value="aaaatester">aaaatester</option>
</select>
</div>
<div id="visualization"></div>
I would suggest, however, that if you are going to have a filter like that, where your initial query is unfiltered, that you switch to using a CategoryFilter to filter your data in the browser instead of making a query to the server every time the user changes the filter. The only time making repeated queries to the server makes sense is when the total traffic to and from the server is likely to be substantially lower using multiple filtered queries than one single unfiltered query.

Related

Why does Django/console give me an error of missing value for stripe.confirmCardPayment intent secret, saying it should be a client secret string?

I'm trying to learn this tutorial, the custom payment flow last bit to integrate stripe with Django
https://justdjango.com/blog/django-stripe-payments-tutorial
in my views.py, I have these views
class StripeIntentView(View):
def post(self, request, *args, **kwargs):
try:
req_json = json.loads(request.body)
customer = stripe.Customer.create(email=req_json['email'])
price = Price.objects.get(id=self.kwargs["pk"])
intent = stripe.PaymentIntent.create(
amount=price.price,
currency='usd',
customer=customer['id'],
metadata={
"price_id": price.id
}
)
return JsonResponse({
'clientSecret': intent['client_secret']
})
except Exception as e:
return JsonResponse({'error': str(e)})
class CustomPaymentView(TemplateView):
template_name = "custom_payment.html"
def get_context_data(self, **kwargs):
product = Product.objects.get(name="Test Product")
prices = Price.objects.filter(product=product)
context = super(CustomPaymentView, self).get_context_data(**kwargs)
context.update({
"product": product,
"prices": prices,
"STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLIC_KEY
})
return context
and in my urls I have
from django.contrib import admin
from django.urls import path
from products.views import stripe_webhook
from products.views import StripeIntentView, CustomPaymentView
urlpatterns = [
path('admin/', admin.site.urls),
path('create-payment-intent/<pk>/', StripeIntentView.as_view(), name='create-payment-intent'),
path('custom-payment/', CustomPaymentView.as_view(), name='custom-payment')
and in my custom_payment.html I have
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Custom payment</title>
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
<link rel="stylesheet" href="{% static 'products/global.css' %}">
</head>
<body>
<section>
<div class="product">
<div class="description">
<h3>{{ product.name }}</h3>
<hr />
<select id='prices'>
{% for price in prices %}
<option value="{{ price.id }}">${{ price.get_display_price }}</option>
{% endfor %}
</select>
</div>
<form id="payment-form">{% csrf_token %}
<input type="text" id="email" placeholder="Email address" />
<div id="card-element">
<!--Stripe.js injects the Card Element-->
</div>
<button id="submit">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Pay</span>
</button>
<p id="card-error" role="alert"></p>
<p class="result-message hidden">
Payment succeeded, see the result in your
Stripe dashboard. Refresh the page to
pay again.
</p>
</form>
</div>
</section>
<script>
var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
var stripe = Stripe("{{ STRIPE_PUBLIC_KEY }}");
document.querySelector("button").disabled = true;
var elements = stripe.elements();
var style = {
base: {
color: "#32325d",
fontFamily: 'Arial, sans-serif',
fontSmoothing: "antialiased",
fontSize: "16px",
"::placeholder": {
color: "#32325d"
}
},
invalid: {
fontFamily: 'Arial, sans-serif',
color: "#fa755a",
iconColor: "#fa755a"
}
};
var card = elements.create("card", { style: style });
// Stripe injects an iframe into the DOM
card.mount("#card-element");
card.on("change", function (event) {
// Disable the Pay button if there are no card details in the Element
document.querySelector("button").disabled = event.empty;
document.querySelector("#card-error").textContent = event.error ? event.error.message : "";
});
var form = document.getElementById("payment-form");
form.addEventListener("submit", function(event) {
event.preventDefault();
var selectedPrice = document.getElementById("prices").value
// Complete payment when the submit button is clicked
fetch(`/create-payment-intent/${selectedPrice}/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
'X-CSRFToken': csrftoken
},
body: JSON.stringify({
email: document.getElementById('email').value
})
})
.then(function(result) {
return result.json();
})
.then(function(data) {
payWithCard(stripe, card, data.clientSecret);
});
});
// Calls stripe.confirmCardPayment
// If the card requires authentication Stripe shows a pop-up modal to
// prompt the user to enter authentication details without leaving your page.
var payWithCard = function(stripe, card, clientSecret) {
loading(true);
stripe
.confirmCardPayment(clientSecret, {
payment_method: {
card: card
}
})
.then(function(result) {
if (result.error) {
// Show error to your customer
showError(result.error.message);
} else {
// The payment succeeded!
orderComplete(result.paymentIntent.id);
}
});
};
/* ------- UI helpers ------- */
// Shows a success message when the payment is complete
var orderComplete = function(paymentIntentId) {
loading(false);
document
.querySelector(".result-message a")
.setAttribute(
"href",
"https://dashboard.stripe.com/test/payments/" + paymentIntentId
);
document.querySelector(".result-message").classList.remove("hidden");
document.querySelector("button").disabled = true;
};
// Show the customer the error from Stripe if their card fails to charge
var showError = function(errorMsgText) {
loading(false);
var errorMsg = document.querySelector("#card-error");
errorMsg.textContent = errorMsgText;
setTimeout(function() {
errorMsg.textContent = "";
}, 4000);
};
// Show a spinner on payment submission
var loading = function(isLoading) {
if (isLoading) {
// Disable the button and show a spinner
document.querySelector("button").disabled = true;
document.querySelector("#spinner").classList.remove("hidden");
document.querySelector("#button-text").classList.add("hidden");
} else {
document.querySelector("button").disabled = false;
document.querySelector("#spinner").classList.add("hidden");
document.querySelector("#button-text").classList.remove("hidden");
}
};
</script>
</body>
</html>
The tutorial was missing a csrf token so I added that and the card element loaded up, and also I had to add an id of prices to the select
Then I got this error
(index):1 Uncaught (in promise) IntegrationError: Missing value for stripe.confirmCardPayment intent secret: value should be a client_secret string.
at X ((index):1)
at Q ((index):1)
at uo ((index):1)
at (index):1
at (index):1
at e.<anonymous> ((index):1)
at e.confirmCardPayment ((index):1)
at payWithCard ((index):104)
at (index):94
Can anyone help me with this ? Thanks
i would suggest adding an additional line to check what is the value of data (and data.clientSecret). It looks like clientSecret may not have a value, or may not be a string.
.then(function(data) {
console.log(data);
payWithCard(stripe, card, data.clientSecret);
});
You would then need to trace why clientSecret does not have the expected value.

Google Visualization - Select Handler not working

I'm hoping this is a problem that's really easy to fix. Having copied all of the necessary code from the Google Visualization site, everything is working with one exception. I have a data table where, if I select a row, the select handler is called - but I am unable to get table.getSelection() to work
I've seen a suggestion that I might need to include getChart(), but that doesn't fix it (at least not in any of the ways I tried).
In the extract below, I get the first alert message when selecting a row, but not the second, as the code stops running at the table.getSelection() line.
Can anyone suggest what the problem might be?
Many thanks!
<html>
</body>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable_1);
function drawTable_1() {
js_booking = <?php echo json_encode($arr_booking); ?>;
js_name = <?php echo json_encode($arr_name); ?>;
var data = new google.visualization.DataTable();
data.addColumn('string', 'Booking');
data.addColumn('string', 'Name');
for (i = 0; i < 5; i++) {
data.addRows([
[js_booking[i], js_name[i]]
]);
}
var table = new google.visualization.Table(document.getElementById('table_div_1'));
table.draw(data, {showRowNumber: false, sort: 'disable', width: '95%', allowHtml:true});
google.visualization.events.addListener(table, 'select', selectHandler);
}
function selectHandler(e) {
alert('A table row was selected');
var selection = table.getSelection();
alert('Selection identified');
}
</script>
</head>
<body>
<div id="table_div_1">Loading...</div>
</body>
<br>
</html>
don't really see a problem with the code, seems to work fine here.
only minor issue...
generally, chart events should be assigned after the chart is created but before the chart is drawn.
see following working snippet...
google.charts.load('current', {
packages: ['table']
}).then(function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Booking');
data.addColumn('string', 'Name');
for (var i = 0; i < 5; i++) {
data.addRow(['Booking ' + (i + 1), 'Name ' + (i + 1)]);
}
var table = new google.visualization.Table(document.getElementById('table_div_1'));
google.visualization.events.addListener(table, 'select', selectHandler);
table.draw(data, {showRowNumber: false, sort: 'disable', width: '95%', allowHtml:true});
function selectHandler(e) {
console.log('A table row was selected');
var selection = table.getSelection();
console.log('Selection identified', JSON.stringify(selection));
}
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div_1"></div>

Select2, need to group results into one for display

I use "multiple select boxes" (select2 examples) and I want to group showing results:
like (only if selected more then X options):
Whithout this the field with the results will be too large. Also, I don't want to make a scroll in the field results.
Is there any ready solution to do this?
I created the solution:
$(document).ready(function() {
$(".test").select2();
});
function select_grouping(obj) {
var min_grouping_count = 3;
var title = ' elements selected';
var count = 0;
if (obj.children('li').length > min_grouping_count) {
if (obj.children('li').length > min_grouping_count) {
count = obj.children('li').length - 1;
obj.children('li').each(function(index, el) {
if (index > 0 && index < count) {
$(this).remove();
}
});
}
obj.children('li:eq(0)').html(count + title);
}
}
$(".test").on("select2:select", function(obj) {
var obj = $('#filtr_test').find('.select2-selection__rendered');
select_grouping(obj);
});
$(".test").on("select2:unselect", function(obj) {
var obj = $('#filtr_test').find('.select2-selection__rendered');
select_grouping(obj);
});
.test {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<div id="filtr_test">
<select class="test" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
</select>
</div>

Fusion Tables Layer Query permanent tile loading issues

I've been using Google Fusion Tables periodically for a few years, though I'm still a novice.
I've recently been charged with querying one of my tables on a geo-spatial relationship. I found a great example that functions exactly as I need it to, and updated the code with my tableId, ensured that the location column was exactly the same (spelling, capitalization, etc), but when I try to update the map layer, it gives me a permanent "Data may still be loading. Drag or refresh to find out!" on the tiles. My table is public, the data downloadable... I'm not sure what I'm missing.
I'm stumped. I've included the code below and simply used // to disable the tableid from the example.
Any assistance/suggestions would be greatly appreciated!
~Nicole
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Austin TX Delivery Locations</title>
<style>
body { font-family: Arial, sans-serif; padding: 0px; margin: 0px; }
#map_canvas { height: 80%; width:100%; }
#query{font-family:courier;}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var tableid = '11QnfV_1v3N5GQs70e13SRxGR6_zYOSFJlCpMuD3C';
//var tableid = 790805;
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(30.35, -97.70),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'click', function(event) {
latlng = event.latLng;
updateQuery();
});
query = {
select: 'address',
from: tableid
}
layer = new google.maps.FusionTablesLayer(tableid);
layer.setMap(map);
}
function updateQuery(){
var limit = document.getElementById('limit').value;
var lat = parseInt(latlng.lat() * 1000) / 1000;
var lng = parseInt(latlng.lng() * 1000) / 1000;
query = "SELECT address FROM " + tableid;
query += " ORDER BY ST_Distance(address, LatLng(" + lat + ',' + lng + "))";
query += " LIMIT " + limit;
layer.setQuery(query);
document.getElementById('query').innerHTML = layer.getQuery();
}
</script>
</head>
<body onLoad="initialize()">
<div id="map_canvas"></div>
<input type="text" id="limit" value="50" onChange="javascript:updateQuery()"/>
<div id="query"></div>
</body>
</html>
When you see the ""Data may still be loading." message it usually means your query is invalid.
Your example has an old "numeric" table id. The syntax for the new "encrypted" table ids is different (and as currently documented)
Constructor Description
FusionTablesLayer(options:FusionTablesLayerOptions) A layer that displays data from a Fusion Table.
Change:
query = {
select: 'address',
from: tableid
}
layer = new google.maps.FusionTablesLayer(tableid);
layer.setMap(map);
To:
query = {
select: 'address',
from: tableid,
};
layer = new google.maps.FusionTablesLayer({query: query });
layer.setMap(map);
And your query in updateQuery to:
query = {
select: 'address',
from: tableid,
limit: limit,
orderBy: ST_Distance(address, LATLNG(" + lat + ',' + lng + "))"
}
layer.setQuery(query);
working fiddle
code snippet:
var tableid = '11QnfV_1v3N5GQs70e13SRxGR6_zYOSFJlCpMuD3C';
//var tableid = 790805;
var latlng;
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(30.35, -97.70),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'click', function(event) {
latlng = event.latLng;
updateQuery(latlng);
});
query = {
select: 'address',
from: tableid
};
layer = new google.maps.FusionTablesLayer({
query: query
});
layer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
function updateQuery(latlng) {
var limit = document.getElementById('limit').value;
query = {
select: 'address',
from: tableid,
limit: limit,
orderBy: 'ST_Distance(address, LATLNG(' + latlng.lat() + ',' + latlng.lng() + '))'
}
layer.setQuery(query);
var queryObj = layer.getQuery()
var queryStr = "from:" + queryObj.from + "<br>";
queryStr += "select:" + queryObj.select + "<br>";
queryStr += "limit:" + queryObj.limit + "<br>";
queryStr += "orderBy:" + queryObj.orderBy + "<br>";
document.getElementById('query').innerHTML = queryStr;
}
html,
body {
font-family: Arial, sans-serif;
padding: 0px;
margin: 0px;
height: 100%;
width: 100%;
}
#map_canvas {
height: 80%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
<input type="text" id="limit" value="50" onChange="javascript:updateQuery()" />
<div id="query"></div>

Google Visualization Line Chart using Google Sheet Code Example

I'm looking for sample code for using a Google Sheet as the source data and make a fairly simple line chart using Google Visualization.
I noticed that the new Google Sheets don't include a script in the "Share Chart" function, they offer a IFRAME and the width/height doesn't work. So, I'm looking to do it with Google Visualizations.
Here is my sample chart.
Thank you for the help.
Edited...
Here is my spreadsheet.
Here is my HTML file.
<html>
<head>
<script type="text/javascript">
function drawChart() {
var query = new google.visualization.Query('http://docs.google.com/spreadsheet/tq?key=14MXilv-uhEAUxDzVB7qVCCmQYqkmWvqqaBOXeBsS04k&gid=0');
query.setQuery('SELECT A, B, C, D, E');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.querySelector('linechart'));
chart.draw(data, {
height: 400,
width: 600
});
});
}
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChart
});
</script>
<title>Data from a Spreadsheet</title>
</head>
<body>
<span id="linechart"></span>
</body>
</html>
It doesn't draw. I've tried various selection in the spreadsheet like avoiding column A, no go. What am I doing wrong?
Here's some example code to get you started:
function drawChart() {
var query = new google.visualization.Query('http://docs.google.com/spreadsheet/tq?key={spreadsheet key}&gid=0');
query.setQuery('SELECT A, B, C');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(data, {
height: 400,
width: 600
});
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
You would need to replace the {spreadsheet key} in the URL with your own spreadsheet key (eg: 'http://docs.google.com/spreadsheet/tq?key=1234567890&gid=0') and change the query to select the appropriate columns from your spreadsheet.
In your page's HTML, you need to have a container div that matches the ID used when creating the chart ('chart_div' in this case):
<div id="chart_div"></div>