flask ajax json html,python - Posting JSON to flask template - Stack Overflow

I've been banging my head against a wall trying to work out how to firstly get JSON data returned from my search (which I've now solved thankfully) and to then update my jinja template with the JSON data spewed out.

I've tried a few methods but I seem to be going around in circles and as I'm not very experienced with either AJAX or Flask I tend to cause more problems than I can fix.

I have an AJAX file but I don't believe it is working (if it is even correct) but I'm guessing that this needs to be instructed to take the data and put it into the correct table/area of the rendered template? my question is how can I make this happen?

Below is my app.py

from flask import request, jsonify

from flask import Flask

from flask_sqlalchemy import SQLAlchemy

from flask_bootstrap import Bootstrap

from flask import render_template

from sqlalchemy import create_engine

from flask_marshmallow import Marshmallow

import json

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:test@localhost/postgres'

engine = create_engine('postgresql+psycopg2://postgres:test@localhost/postgres')

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

app.debug = True

app.config['SQLALCHEMY_ECHO'] = True

db=SQLAlchemy(app)

Bootstrap(app)

ma=Marshmallow(app)

# classes

class Sdctest(db.Model):

startchass= db.Column (db.Text, primary_key=True)

cusname= db.Column (db.Text)

chassistype1= db.Column (db.Text)

axleqty= db.Column (db.Integer)

tyres= db.Column (db.Text)

extlength= db.Column (db.Text)

neck= db.Column (db.Text)

stepheight= db.Column (db.Text)

reardeckheight= db.Column (db.Text)

siderave= db.Column (db.Text)

steer= db.Column (db.Text)

sockets= db.Column (db.Text)

containerstwistlock= db.Column (db.Text)

headboard= db.Column (db.Text)

class TableSchema(ma.Schema):

class Meta:

fields = ('startchass', 'cusname', 'chassistype1', 'axleqty', 'tyres', 'extlength', 'neck', 'stepheight', 'reardeckheight', 'siderave', 'steer', 'sockets', 'containerstwistlock', 'headboard')

tables = TableSchema()

tabless = TableSchema(many=True)

#routes

@app.route('/')

def index():

return render_template('index.html')

@app.route('/platform', methods=['GET', 'POST'])

def curtainsider():

options = db.session.query(Sdctest.chassistype1).distinct().all()

axleopts = db.session.query(Sdctest.axleqty).distinct().all()

# enables passing user input to the variable

if request.method == 'POST':

# query parameters and their corresponding database columns

param_columns = {

"startchass": "startchass",

"cusname": "cusname",

"chassistype1": "chassistype1",

"axleqty": "axleqty",

"tyres": "tyres",

"siderave": "siderave",

"steer": "steer",

"sockets": "sockets",

"containerstwistlock":"containerstwistlock",

"headboard": "headboard",

}

param_column2 = {

"startchass": "startchass",

"extlength": "extlength",

"neck": "neck",

"stepheight": "stepheight",

"reardeckheight": "reardeckheight",

}

# Get all of the column filters where the parameters aren't empty

filters = {

column: request.form[param]

for param, column in param_columns.items()

if request.form.get(param, "") != ""

}

filters2 = {

column: request.form[param]

for param, column in param_column2.items()

if request.form.get(param, "") != ""

}

#filter most columns using fuzzy match

query = Sdctest.query

for column, value in filters.items():

query = query.filter(getattr(Sdctest, column).ilike(f'%{value}%')) .order_by(Sdctest.startchass.desc())

for column, value in filters2.items():

query = query.filter(getattr(Sdctest, column).ilike(f'{value}')).order_by(Sdctest.startchass.desc())

results2 = query.all()

result2 = tabless.dump(results2, object)

# renders the template

return render_template('platform.html')

return jsonify(result2)

else:

return render_template('platform.html', options=options)

if __name__ == "__main__":

run_server()`

and this is my template:

body {

padding: 15px;

background-image: url("/static/bg.png");

background-repeat: no-repeat;

}

.table-hideable td,

.table-hideable th {

width: auto;

transition: width .5s, margin .5s;

}

.btn-condensed.btn-condensed {

padding: 0px 0px 0px 0px;

box-shadow: none;

}

.hide-col {

width: 0 !important;

height: 0 !important;

display: none !important;

overflow: hidden !important;

margin: 0 !important;

padding: 0 !important;

border: none !important;

}

.thbg

{

background-image: url("/static/fieldbg.png");

}

.thbgg

{

background-color:#b21f2d ;

color: #FFF;

}

Sales Search
ALPHA
sdclogopng.png

Select chassis type

{% for option in options %}

{{ option[0] }}

{% endfor %}

Axle quantity

{% for axleopt in axleopts %}

{{ axleopt[0] }}

{% endfor %}

search for specific items/text here:
Click on a column header to exclude it from your results

{% block body %}

Chassis Number Customer nameChassis TypeAxlesTyreExternal LengthNeckStep heightRear Deck heightSideraveSteerSocketsTwistlocksHeadboard

{% for item in result2 %}

{{ item.startchass }}{{ item.cusname }}{{ item.chassistype1 }}{{ item.axleqty }}{{ item.tyres }}{{ item.extlength }}{{ item.neck }}{{ item.stepheight }}{{ item.reardeckheight }}{{ item.siderave }}{{ item.steer }}{{ item.sockets }}{{ item.containerstwistlock }}{{ item.headboard }}

{% endfor %}

Click here to show hidden columns

{% endblock %}

$(document).ready(function(){

$("#myInput").on("keyup", function() {

var value = $(this).val().toLowerCase();

$("#myTable tr").filter(function() {

$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)

});

});

});

and lastly my (probably not working) AJAX file:

$(function() {

$('form').on('submit', function(e){

$.ajax({

url: '/platform',

data: $('form').serialize(),

type: 'POST',

cusname:cusname,

success: function(response) {

console.log(response);

},

error: function(error) {

console.log(error);

}

});

});

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值