Stripe custom button with Python/Flask - python

I can make the simple button or default button work but as there is no option to custom css I need to use "Custom" stripe button. Following is the simple and custom form I am using where simple one works fine but don't know how to make custom work. Currently it is doing nothing when I click and enter information. But Default button works just fine.
View:
#app.route('/monthly', methods=['GET', 'POST'])
def monthly_charged():
if not user_authorized():
return redirect('/')
amount = 1495
# customer
key = stripe_keys['publishable_key']
print key
charge_all = stripe.Charge.list(limit=10000)
charge_dic = {}
charge_list = []
for charge_data in charge_all:
charge_dic['Amount'] = "$" + str(float(charge_data.amount) / 100) + " " + charge_data.currency.upper()
charge_dic['Description'] = charge_data.description
charge_dic['Name'] = charge_data.receipt_email
charge_dic['Date'] = str(datetime.datetime.fromtimestamp(charge_data.created))
charge_list.append(charge_dic)
charge_dic = {}
data = get_profile_data(session['auth_token'])
profile_data = data['StudentProfile']
student_id = profile_data.id
student = get_profile_data(session['auth_token'])['StudentProfile']
pkg = Package.query.filter_by(student_id=profile_data.id).first()
if pkg:
flash('You already have an active subscription.')
else:
stripe_token = request.form['stripeToken']
email = request.form['stripeEmail']
try:
customer = stripe.Customer.create(
email=email,
source=request.form['stripeToken']
)
subscription = stripe.Subscription.create(
customer=customer.id,
plan="monthly",
)
student_id = profile_data.id
student.stripe_customer_id = customer.id
student.stripe_subscription_id = subscription.id
package = Package(
student_id=student_id,
stripe_id = customer.id,
student_email=request.form['stripeEmail'],
is_active=True,
package_type='monthly',
subscription_id=subscription.id
)
dbase.session.add(package)
flash("You've successfylly subscribed for monthly package.")
dbase.session.commit()
except stripe.error.CardError as e:
# The card has been declined
body = e.json_body
err = body['error']
return redirect(url_for('packages', key=key, amount=amount))
Simple or Default Stripe Button:
<form action="/monthly" method="post" >
<div class="form-group">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_YgHVTCLIMQLW4NV6ntnJPAXs"
data-description="Monthly Package"
data-name="Monthly"
data-amount="10000"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto">
</script>
</div>
</form>
Custom Stripe Button:
<form action="/monthlycharged" method="post">
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Enroll</button>
<style>
#customButton{
width:100px;
height:30px;
background-color:red;
color:white;
border:2px solid red;
}
</style>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Monthly',
description: 'monthly',
amount: 10000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
</form>

You need to submit your form in the token: function() {} of StripeCheckout.configure.
Here's an example of how to do that: https://jsfiddle.net/osrLsc8m/

Related

Adding User Registartion to Database Flask

I'm following a tutorial to add new users to my database via a html form and flask. I'm able to run the code using the html template with: localhost/5000
But if I enter the data that should be add to the database I get the following error:
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
with this url: http://localhost:5000/sign_in?stage=login
Python code:
#app.route("/")
def showForm():
# show our html form to the user
t_message = "Python and Postgres Registration Application"
return render_template("register.html", message = t_message)
#app.route("/register", methods=["POST","GET"])
def register():
# get user input from the html form
t_email = request.form.get("t_email", "")
t_password = request.form.get("t_password", "")
# check for blanks
if t_email == "":
t_message = "Please fill in your email address"
return render_template("register.html", message = t_message)
if t_password == "":
t_message = "Please fill in your password"
return render_template("register.html", message = t_message)
# hash the password they entered
t_hashed = hashlib.sha256(t_password.encode())
t_password = t_hashed.hexdigest()
# database insert
t_host = "localhost"
t_port = "5432"
t_dbname = "register_dc"
t_user = "postgres"
t_pw = "=5.k7wT=!D"
db_conn = psycopg2.connect(host=t_host, port=t_port, dbname=t_dbname, user=t_user, password=t_pw)
db_cursor = db_conn.cursor()
# We take the time to build our SQL query string so that
# (a) we can easily & quickly read it
# (b) we can easily & quickly edit or add/remote lines
# The more complex the query, the greater the benefits
s = "INSERT INTO public.users "
s += "("
s += " t_email"
s += ", t_password"
s += ") VALUES ("
s += " '" + t_email + "'"
s += ",'" + t_password + "'"
s += ")"
db_cursor.execute(s)
try:
db_conn.commit()
except psycopg2.Error as e:
t_message = "Database error: " + e + "/n SQL: " + s
return render_template("register.html", message = t_message)
t_message = "Your user account has been added."
return render_template("register.html", message = t_message)
if __name__ == "__main__":
app.run(debug=True)
HTML code:
<script language="JavaScript" type="text/javascript">
function checkform (form)
{
/* isEmpty() returns true and alerts the user if they left a field empty */
function isEmpty (fixwhat, s_called)
{
if (fixwhat=="")
{
alert("Please enter " + s_called);
return true;
} else {
return false;
}
}
/* charCheck() returns false and alerts the user if they used any non-alphanumeric characters */
function charCheck(fixwhat)
{
var validchars = '#-_.0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
if(isValid(fixwhat,validchars))
{
return true;
} else {
alert("Please use only letters or numbers in this field");
return false;
}
}
/* isValid is used by the charCheck() function to look through each 'validchars' one at a time */
function isValid(string,validchars)
{
for (var i=0; i< string.length; i++)
{
if (validchars.indexOf(string.charAt(i)) === -1) {return false;}
}
return true;
}
// Check for empty fields
if (is_empty (form.t_email.value,"your email address")) { form.t_email.focus(); return false;}
if (is_empty (form.t_password.value,"your password")) { form.t_password.focus(); return false;}
//check for weird chars
if (charCheck(form.t_email.value)===false) {form.t_email.focus(); return false;}
if (charCheck(form.t_password.value)===false) {form.t_password.focus(); return false;}
return true ;
}
</script>
<div class='container'>
<form id='frmSignIn' name='frmSignIn' action='/sign_in?stage=login' method='post' onsubmit='return checkform(this);'>
<div class="form-row">
<label for="Email">Email address:</label>
<input type="text" id="t_email" name="t_email">
</div>
<div class="form-row">
<label for="Email">Password:</label>
<input type="text" id="t_password" name="t_password">
</div>
<div class="form-row">
<input type="submit" id="btn_submit_sign_in" value='Sign In'>
</div>
</form>
You are using the route /sign_in in your browser (and in your template), but you declared your route as /register, thus a 404 is returned.

Generate dynamic div containers on submit in Flask app

I am new in Flask. My goal is to generate dynamic div containers every time I upload a dxf file and next submit happens. For example: one file uploaded- one div shown; two files uploaded- two divs shown and so on.
I can convert uploaded dxf files to .png images and I would like to show these images in div elements displayed after every upload.
I use input tag to upload files (type='file') and Java Script to generate dynamic elements (divs and their child tags).
The problem is that every time I upload file, the template is loading again and no new content is shown except the image of the last uploaded dxf. Please, give me a piece of advice to solve it.
HTML
...
<form enctype="multipart/form-data" id="uploadForm" action="/upload_files" name="uploadForm" method="post">
DXF file: <input type="file" id="dxfUpload" onchange="form.submit(); createConfigure();" name="dxfUpload" />
<div id="calcHolder" name="calcHolder">
<script type="text/javascript">
function createConfigure() {
var div = document.createElement("div");
div.id = "dxf-"+Math.random() * 100000000000000000 + "-"
+ window.performance.now() * 100000000000000000;
id_div=div.id;
div.className = 'border pad';
div.style.width = "640px";
div.style.height = "200px";
document.getElementById("calcHolder").appendChild(div);
var img = document.createElement("img");
img.setAttribute("src", "{{url_for('static', filename=dxfName+'.png')}}");
img.setAttribute("alt", "no image");
img.setAttribute("height", "120px");
img.setAttribute("width", "120px");
document.getElementById(id_div).appendChild(img);
var array = ["Carbon Steel","Stainless Steel","Aluminium"];
var selectMaterial = document.createElement("select");
document.getElementById(id_div).appendChild(selectMaterial);
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i];
option.text = array[i];
selectMaterial.appendChild(option);
}
var selectThickness = document.createElement("select");
document.getElementById(id_div).appendChild(selectThickness);
for (i = 1; i <= 16; i++) {
var opt = document.createElement('option');
//opt.value = i;
opt.innerHTML = i + ' mm';
selectThickness.appendChild(opt);
}
var quantity = document.createElement("input")
quantity.type="number";
quantity.value="1";
quantity.name="quantity";
quantity.min="1";
quantity.max="50";
quantity.onkeyup= function maxReach(){if(quantity.value > 50) quantity.value=50;};
document.getElementById(id_div).appendChild(quantity);
var btn = document.createElement("button");
btn.innerHTML = "Delete";
btn.type = "button";
document.getElementById(id_div).appendChild(btn);
btn.onclick = function() {div.remove();};
}
</script>
{{ html | safe }}
</div>
</form>
...
Python
#app.route('/upload_files', methods=['POST'])
def upload_files():
try:
if request.method == 'POST':
dxf_file = request.files['dxfUpload']
full_filename = os.path.join(app.config['UPLOAD_FOLDER'],dxf_file.filename)
dxf_file.save(full_filename)
first = DXF2IMG()
first.convert_dxf2img([full_filename],img_format='.png')
html="<img src="+url_for('static', filename=dxf_file.filename+'.png' )+" width='120' height='120' />"
return render_template('upload_files.html',dxfName=dxf_file.filename, html=html)
except:
...
#something happens
The result now
Desired result
Once the form.submit() function is executed, the form will be sent as a regular post request. For this reason, the following function is no longer executed and the entire page is reloaded.
In order to submit the form and change the content of the existing page, it is necessary to use AJAX.
This example shows you how to submit the form to the server and receive a JSON response containing the URLs of the received file and the generated image.
As soon as the submit button is pressed, the form data is packed into a FormData object and sent via AJAX using the fetch function. The browser's default behavior for a submit event is suppressed and the form is reset. The received file is processed by the server and the associated URLs are sent back to the client in JSON format. Now the document can be changed with the received data.
Remember this is just a minimal example to help you achieve your goals and implement your concept.
Flask (app.py)
import os
import ezdxf
from ezdxf.addons.drawing import matplotlib
from flask import Flask
from flask import (
jsonify,
make_response,
render_template,
url_for
)
from werkzeug.utils import secure_filename
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
def dxf2png(source, target):
doc = ezdxf.readfile(source)
msp = doc.modelspace()
auditor = doc.audit()
if auditor.has_errors:
raise Exception('Conversion failed.')
matplotlib.qsave(doc.modelspace(), target)
#app.route('/upload', methods=['POST'])
def upload():
if 'dxf-file' in request.files:
file = request.files['dxf-file']
if file.filename != '':
filename = secure_filename(file.filename)
filepath = os.path.join(app.static_folder, filename)
destname, _ = os.path.splitext(filename)
destname = f'{destname}.png'
destpath = os.path.join(app.static_folder, destname)
file.save(filepath)
try:
dxf2png(filepath, destpath)
except:
os.remove(filepath)
return make_response('', 400)
return make_response(
jsonify(
target=url_for('static', filename=filename),
preview=url_for('static', filename=destname)
),
200
)
return make_response('', 400)
HTML (templates/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
<style media="screen">
.preview {
width: 120px;
height: auto;
}
</style>
</head>
<body>
<form name="dxf-upload" method="post" enctype="multipart/form-data">
<input type="file" name="dxf-file" />
<input type="submit" />
</form>
<div id="dxf-files"></div>
<script type="text/javascript">
((uri) => {
function createPreview(target, preview) {
const divElem = document.createElement('div');
divElem.innerHTML = `<img src="${preview}" class="preview" />`;
const outElem = document.getElementById('dxf-files');
outElem.append(divElem);
}
const form = document.querySelector('form[name="dxf-upload"]');
form.addEventListener('submit', evt => {
evt.preventDefault();
const formData = new FormData(evt.target);
fetch(uri, {
method: 'POST',
body: formData
}).then(resp => resp.json())
.then(data => {
const { target, preview } = data;
createPreview(target, preview);
});
evt.target.reset();
});
})({{ url_for('.upload') | tojson }});
</script>
</body>
</html>

Theme Choosing Option for a Django Project not working properly

Helloo,
I am following a tutorial to allow User to select Light/Dark Mode using HTML, CSS, JS.
I have following documentation and tutorial but the issue is that the content of the page itself is not showing and I am not sure the reason.
So what I did is I created 2 css files dark and light, and create a mode application with the settings.
I am currently receiving an error:
django.contrib.auth.models.User.setting.RelatedObjectDoesNotExist: User has no setting.
To start here is the base.html
<link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet">
<!-- Mode -->
<div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right">
<button onclick="swapStyle('css/app-light.css')" type="button" class="btn btn-secondary">Light Mode</button>
<button onclick="swapStyle('css/app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button>
</div>
<!-- Mode -->
<script type="text/javascript">
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
var cssFile = "{% static 'css' %}"
function swapStyles(sheet){
document.getElementById('mystylesheet').href = cssFile + '/' + sheet
localStorage.setItem('theme', sheet)
updateTheme(sheet)
}
function loadSettings(){
//Call data and set local storage
var url = "{% url 'mode:user_settings' %}"
fetch(url, {
method:'GET',
headers:{
'Content-type':'application/json'
}
})
.then((response) => response.json())
.then(function(data){
console.log('Data:', data)
var theme = data.value;
if (theme == 'light.css' || null){
swapStyles('light.css')
}else if(theme == 'dark.css'){
swapStyles('dark.css')
}
})
}
loadSettings()
function updateTheme(theme){
var url = "{% url 'mode:update_theme' %}"
fetch(url, {
method:'POST',
headers:{
'Content-type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'theme':theme})
})
}
</script>
Here is the model.py
class Setting(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
value = models.CharField(max_length=200)
def __str__(self):
return self.name
here is the views.py
def index(request):
return render(request, 'base.html')
def userSettings(request):
user, created = User.objects.get_or_create(id=1)
setting = user.setting
seralizer = UserSerailizer(setting, many=False)
return JsonResponse(seralizer.data, safe=False)
def updateTheme(request):
data = json.loads(request.body)
theme = data['theme']
user, created = User.objects.get_or_create(id=1)
user.setting.value = theme
user.setting.save()
print('Request:', theme)
return JsonResponse('Updated..', safe=False)
Here is the serializer.py
from .models import *
class UserSerailizer(serializers.ModelSerializer):
class Meta:
model = Setting
fields = '__all__'
Here is urls.py
app_name = 'mode'
urlpatterns = [
path('', views.index, name="index"),
path('user_settings/', views.userSettings, name="user_settings"),
path('update_theme/', views.updateTheme, name="update_theme"),
]
Here is the traceback
Traceback (most recent call last):
File "C:\Users\Ahmed\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Ahmed\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Ahmed\Desktop\Project\mode\views.py", line 17, in userSettings
setting = user.setting
File "C:\Users\Ahmed\Desktop\Project\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 421, in __get__
raise self.RelatedObjectDoesNotExist(
django.contrib.auth.models.User.setting.RelatedObjectDoesNotExist: User has no setting.
You need to handle the case when a user will not have a setting in userSettings function.
def userSettings(request):
user, created = User.objects.get_or_create(id=1)
setting = getattr(user, 'setting', None)
if setting:
seralizer = UserSerailizer(setting, many=False)
return JsonResponse(seralizer.data, safe=False)
else:
return JsonResponse({'message': "User don't have a setting."}, safe=False)
And also make sure that updateTheme function works perfectly. If it doesn't work try following.
def updateTheme(request):
data = json.loads(request.body)
theme = data['theme']
user, created = User.objects.get_or_create(id=1)
setting = Setting.objects.get_or_create(user=user, value=theme, name='a name')
setting.save()
print('Request:', theme)
return JsonResponse('Updated..', safe=False)
Note that in the name field of Setting model you didn't pass null=True. So you have to pass name when creating a setting of a user.
Also in your base.html you are using onclick="swapStyle()" yet your javascript function is function swapStyles(){}. Change this
setting = getattr(user, 'setting', None)

Value of JSON object on render_template Python

I have a profile method and a profile.html template.
profile.html has a drop-down list of user e-mails. When I select one of them, a modal window appears with this email, and I can send a message to it. I get it via AJAX.
The problem is that born_date and phone_number of this user, which I get from the database are not rendered into a template, and I can not see them in modal window, but I can get them in the console.
def str_value_to_list(text: str):
*_, email_json = re.findall(r'[^ \',()]+', text)
return email_json
#profile page method
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'GET' and 'loggedin' in session:
cur = mysql.connection.cursor()
cur.execute("SELECT firstname, lastname, email FROM users.data WHERE description = 'doctor'")
account = cur.fetchall()
description = account
countries = ['USA','France','Italy','Spain','Australia','New Zealand']
cur = mysql.connection.cursor()
cur.execute("SELECT born_date, phone_number FROM users.data WHERE email = '%s'" % (dtx, ))
account = cur.fetchone()
born = account[0]
num = account[1]
print(born)
print(num)
return render_template(
'profile.html',
id = session['id'],
email = session['email'],
firstname = session['firstname'],
description = description,
countries = countries,
born=born,
num=num
)
#app.route('/api/get_data', methods=['POST'])
def get_data():
if request.method == 'POST':
print('Holy Shit!')
data = request.json
print(str_value_to_list(data['selectedItems'][0]))
cur = mysql.connection.cursor()
cur.execute("SELECT born_date, phone_number FROM users.data WHERE email = '%s'" % str_value_to_list(data['selectedItems'][0]))
account = cur.fetchone()
born = account[0]
num = account[1]
print(born)
print(num)
return jsonify({
'born': born,
'num': num,
})
html
<script type="text/javascript">
function printValue(selectedItem) {
$('#mySelectedValue').html(selectedItem.value);
}
</script>
<h2 class="white-text" style="font-size: 14px; color: #000;">born: {{ born }}</h2>
<h2 class="white-text" style="font-size: 14px; color: #000;">num: {{ num }}</h2>
<script type="text/javascript">
function printValue(selectedItem) {
$('#mySelectedValue').html(selectedItem.value.replace(/[{()}]/g, '').replace(/['"]+/g, '').replace(/[{,}]/g, ''));
console.log(selectedItem.value);
}
function process(selectedItem) {
$('#exampleModalCenter').modal('show')
document.getElementById('#exampleModalCenter')
const data = JSON.stringify({
"selectedItems": $('#sel').val()
});
$.ajax({
url: "/profile",
type: "POST",
contentType: "application/json",
data: data,
success: function (data) {
console.log(data);
},
});
}
function optionClick(selectedItem) {
printValue(selectedItem);
}
</script>
Per your code, you should use Javascript to update the born and num variable inside your Ajax success funtion:
$.ajax({
url: "/api/get_data",
type: "POST",
contentType: "application/json",
data: data,
success: function (data) {
h2 = document.querySelectorAll('.white-text')
h2[0].innerText = `born: ${data.born}`
h2[1].innerText = `num: ${data.num}`
},
});
You didn't put variable born, num in the render_template function, so you are not able to render it using {{ var }}

Flask Form Submit does nothing

Clicking on the submit button literally does nothing. Submitting a blank form will trigger the validation for the required fields, but filling out the form as required results in the form not submitting/submit button doing nothing. The template has the CSRF_Token, Submit Button is in the form tag, and the form tag has an action attribute pointing in the right direction. Chrome doesn't bark any errors so I'm stuck on how to proceed.
views.py
#blueprint.route("register/", methods=['GET', 'POST'])
def register():
"""Renders register page."""
form = RegisterForm()
if request.method == 'POST':
if not form.validate_on_submit():
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=False, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
company, err = get_company(form.organization.data)
if err:
company, err = create_company(form.organization.data)
if err:
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
customer, err = get_or_create_customer(
form.first_name.data + " " + form.last_name.data, form.email.data,
company_id, form.position.data, phone_number
)
if err:
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
if err:
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
else:
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=True, message=success_msg, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
return render_template('main/register.html', page_title="Service Registration",
form=form, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
#blueprint.route("register/", methods=['POST'])
def upload_register():
"""Handles file upload POSTs."""
first_name = request.form.get("first_name")
last_name = request.form.get("last_name")
name = request.form.get("first_name") + " " + request.form.get("last_name")
email = request.form.get("email")
filename = request.form.get("filename")
file_type = request.form.get("file_type")
if filename == '':
response = make_response("No selected file")
return response, 400
if check_file_type(file_type):
filename = clean_filename(filename)
filename = secure_filename(filename)
filename = unique_filename(filename)
response = generate_presigned_post(filename, file_type)
# CREATE DB REFERENCE
url = "http://nevcodocs.s3.amazonaws.com/Uploads/{}".format(filename)
instance = CustomerFileUpload.query.filter_by(url=url).first()
if not instance:
instance = CustomerFileUpload(url=url, email=email, name=name)
db.session.add(instance)
db.session.commit()
else:
instance.update(created_at=datetime.utcnow())
return response, 200
else:
response = make_response("Invalid file type")
return response, 500
javascript/jquery
// Enables/disables form submission and colors button accordingly
var enableSubmit = function(enabled) {
if (enabled) {
$('#submit_ticket').removeAttr('disabled');
$('#submit_ticket').removeAttr('style');
} else {
$('#submit_ticket').attr('disabled', 'disabled');
$('#submit_ticket').attr('style', 'background-color: rgba(244, 121, 32, 0.5) !important; border-color: rgba(244, 121, 32, 0.25) !important;');
}
};
$('#ticket-form').submit(function(event) {
enableSubmit(false);
showSpinner(true);
var validated = true;
var didSelectFile = true;
didSelectFile = validateField('#upload') && validated;
validated = didSelectFile && validated;
if (didSelectFile && !validateContentType()) {
$('invalid-upload-alert').show();
validated = false;
} else {
$('#invalid-upload-alert').hide();
}
if (validated) {
$('#filename').val($('#upload').val());
$('#file_type').val($('#upload').prop('files')[0].type);
$.ajax({
type: 'POST',
url: '/register/',
data: $('#ticket-form').serialize()
}).done(function(data) {
var formData = new FormData();
for (var key in data.data.fields) {
formData.append(key, data.data.fields[key]);
}
formData.append('file', $('#upload').prop('files')[0]);
var req = new XMLHttpRequest();
req.onload = function() {
showSpinner(false);
$('#ticket-form-failed').removeClass("support-form-show");
$('#ticket-form-failed').addClass("support-form-hide");
$('#ticket-form').removeClass("support-form-show");
$('#ticket-form').addClass("support-form-hide");
$('#ticket-form-success').removeClass("support-form-hide");
$('#ticket-form-success').addClass("support-form-show");
};
req.onerror = function() {
showSpinner(false);
$('#ticket-form-failed').removeClass("support-form-hide");
$('#ticket-form-failed').addClass("support-form-show");
};
req.open('POST', data.url);
req.send(formData);
}).fail(function(err) {
showSpinner(false);
$('#ticket-form-failed').removeClass("support-form-hide");
$('#ticket-form-failed').addClass("support-form-show");
});
} else {
showSpinner(false);
enableSubmit(true);
}
{% endif %}
if (!validated) {
event.preventDefault();
showSpinner(false);
enableSubmit(true);
}
});
What you have written looks really complicated, why not try something easy like-
#app.route("/connect",methods=['GET','POST'])
def connect():
if request.method=='GET':
return render_template('connect.html')
if request.method=="POST":
return render_template('Thankyou.html',name=request.form['name])
in you views.py and in your connect.html form just write-
<form name="connect" method="post" action="{{ url_for('connect') }}">
<input class="t1" type="text" id="email" name="email" placeholder="Your Email ID">
<input class="t2" type="text" id="name" name="name" placeholder="name">
<button class="btn btn-primary but" type="submit">Send</button>
</form>
the final page, Thankyou.html can look like this-
<p>Thanks for contacting me, {{ name }} </p>

Categories

Resources