Is it possible to pass data to AJAX without a call?

35 views Asked by At

I am using a combination of Flask and AJAX to make a sortable table (like the example here). However, instead of making an API call, I am already returning a list of dicts, and I would like to use that. This is my function, which asks for user input, and then when given input, posts the table:

@application.route('/users', methods=['GET', 'POST'])
def eshop():
    result = None
    users= None
    counter = 0
    user_listJson= None
    if request.method == 'POST':
        user_input = request.form['user_input']
        users,counter = get_users(user_input)
        result = "Users found: {}".format(counter)
        user_listJson= jsonify(data=users) if users else None
    return render_template('users.html', result=result, user_listJson=user_listJson)

Then I have the following html:

{% extends "base.html" %}
{% block content %}
    <div class="container mt-5">
    <form method="POST" onsubmit="showLoading()" class="mb-3">
        <div class="input-group">
            <input type="text" name="user_input" class="form-control">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>
    <h3 id="loading" style="display: none;">Loading . . .</h3>
    {% if result %}
        <h3>{{ result }}</h3>
        <h4>They are:</h4>
        <table id="data" class="table table-striped">
            <thead>
            <tr>
                <th>First</th>
                <th>Last</th>
                <th>Email</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    {% endif %}
{% endblock %}

{% block scripts %}
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/v/bs5/jq-3.7.0/dt-1.13.8/r-2.5.0/datatables.min.js"></script>
    <script>
        $(document).ready(function () {
            var userList={{ user_listJson}};

            $('#data').DataTable({
                data: userList, // Use the JSON data directly
                columns: [
                    {data: 'First'},
                    {data: 'Last'},
                    {data: 'Email'}
                ],
            });
        });
    </script>
{% endblock %}

I cannot seem to find anything that tells me yay or nay on if this should work, but at the moment, it renders the table headers, but no data to the table. I have confirmed user_listJson= jsonify(data=users) if users else None is successfully passing JSON data thru user_listJson=user_listJson. Thanks in advance!

0

There are 0 answers