简体   繁体   中英

Live updating HTML table using Javascript on input property change with data from SQL database

I'm having a hell of a time here trying to get this to work. I'm pretty sure I've done almost all the research I can trying to solve this, and I just can't figure out where I'm going wrong. So, that being said, thanks in advance for any help you guys can offer.

I'll start by posting my code:

HTML:

{% block main %}
    <form action="{{ url_for('index') }}" method="post">
        <fieldset>
            <div id ="total" class="form-inline">
                <div id="itemBackground" class="col-sm-6">
                    <div id="itemToolBar" class="row">
                        <div class="col-sm-6">
                            <label>
                                Show:
                                <select name="list_length" class="form-control input-sm">
                                    <option value="10">10</option>
                                    <option value="25">25</option>
                                    <option value="50">50</option>
                                    <option value="100">100</option>
                                </select>
                            </label>

                        </div>
                        <div class="col-sm-6" align="right">
                            <label>
                                Search:
                                <input class="form-control input-sm" autocomplete="off" type="textbox" name="q" id="q" placeholder="">
                            </label>
                        </div>
                    </div>

                    <table id="itemTable" name="itemTable" class="table table-hover table-inverse">
                        <thead>
                            <tr id="head">
                                <th>ID</th> 
                                <th>Item</th>
                                <th>Buy</th>
                                <th>Sell</th>
                            </tr>
                        </thead>
                        {% for item in items %}
                            <tr id="rows">
                                <td scope="row">{{ item[0] }}</td>
                                <td>{{ item[1] }}</td>
                                <td>{{ item[2] }}</td>
                                <td>{{ item[3] }}</td>
                            </tr>
                        {% endfor %}
                    </table>
                </div>

                <div id = "vehicleBackground" class="col-sm-6">
                    <table id="vehicleTable" class="table table-hover table-inverse">
                        <thead>
                            <tr id="head">
                                <th>ID</th> 
                                <th>Item</th>
                                <th>Buy</th>
                            </tr>
                        </thead>
                        {% for vehicle in vehicles %}
                            <tr id="rows">
                                <th scope="row">{{ vehicle[0] }}</th>
                                <td>{{ vehicle[1] }}</td>
                                <td>{{ vehicle[2] }}</td>
                            </tr>
                        {% endfor %}
                    </table>
                </div>
            </div>


        </fieldset>
    </form>
{% endblock %}

Python:

# configure application
app = Flask(__name__)

# ensure responses aren't cached
if app.config["DEBUG"]:
    @app.after_request
    def after_request(response):
        response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
        response.headers["Expires"] = 0
        response.headers["Pragma"] = "no-cache"
        return response


# configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = gettempdir()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        if not request.form.get("q"):
            return print("Give me a search query")
        else:
            q = request.form.get("q") + "%"
            print(q)

            conn = sqlite3.connect('items.db')
            db = conn.cursor()

            db.execute("SELECT * FROM items WHERE item LIKE '{}'".format(q))
            itemList = db.fetchall()

            db.execute("SELECT * FROM vehicles")
            vehicleList = db.fetchall()

            db.close()
            conn.close()


            return render_template("index.html", items = itemList, vehicles = vehicleList)

    # else if user reached route via GET (as by clicking a link or via redirect)
    else:

        # configure CS50 Library to use SQLite database
        conn = sqlite3.connect('items.db')
        db = conn.cursor()

        db.execute("SELECT * FROM items")
        itemList = db.fetchall()

        db.execute("SELECT * FROM vehicles")
        vehicleList = db.fetchall()

        db.close()
        conn.close()

        return render_template("index.html", items = itemList, vehicles = vehicleList)

@app.route("/search")
def search():
    """Search for places that match query."""
    print("here")
    # TODO
    q = request.args.get("q") + "%"

    items = db.execute("SELECT * FROM items WHERE item LIKE '{}'".format(q))

    return jsonify(items)

Javascript:

// execute when the DOM is fully loaded
$( document ).ready(function() {
    configure();
});

/**
 * Configures application.
 */
function configure()
{
    // configure typeahead
    $("#q").on('input propertychange paste', function() {
        //$("#q").val("hi");

        // get items matching query (asynchronously)
        var table = "<thead><tr><th>ID</th><th>Item</th><th>Buy</th><th>Sell</th></tr></thead><tr>";

        var parameters = {
            q: $("q").val()
        }; 

        $.getJSON(Flask.url_for("search"), parameters)
        .done(function(data) {
            $('#q').val("hi");
            for (var i=0; i<data.length; i++) {
                obj = data[i];
                for (var key in obj) {
                    table += "<td>" + key + "</td>";
                }
            }
            table += "</tr>";

            $("#itemTable").replaceWith(table);
            //document.getElementById('').innerHTML = table;
        })
        .fail(function() {
            // log error to browser's console
            console.log(errorThrown.toString());
        });
    });

    // give focus to text box
    $("#q").focus();
}

Where I'm stuck is with the javascript when I check for the textbox input to be changed and thus try to update the table with data that matches the query from my database. I do actually make it into the "input propertychange paste" section, I know because I set it to change the textbox value to "hi" whenever anything is typed in the box, but I never make it through the next section where I try to getJson from my /search python function, then format it into a table, and then replace the old table with the one I just made.

I'm not really sure what more information I can give you guys, but I'm sure I'm missing some stuff you need. So let me know if you do. Thanks again in advance for helping me out if you can!

Edit: I should add that my code never even reaches into that getJSON block. As you can see I try to change the value of the input textbox inside of the getJSON call, but the textbox never gets updated to say "hi". Seems like I'm possible calling getJSON wrong? Not sure.

Edit2: Okay, so I did manage to get into the getJSON call now. Thank you for your help with that. But now I'm onto the real part of my question, how would I go about formatting the table after I get the JSON from the SQL database? From what I can tell, I have the formatting at least mostly correct, but I might be having an issue when it comes to removing the old table and inserting the new one.

The selector #itemTable is not matched in HTML. The <table> element name attribute value is "itemTable" ; the element does not have an id set at HTML. Use $("table[name=itemTable]") or set the id to "itemTable" at HTML to be able to use #itemTable selector and match the existing <table> element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM