2

I'm using AJAX to send a user-input form to Flask, where it is processed, used in a query, and the results are sent back as a JSON object. AJAX is called upon form submission, and I'm returning the proper query results. But, when the results are returned, the JSON object is printing to the browser window, not maintaining the template format of the original page.

views.py

@app.route('/table_data', methods=['POST'])
def table_data():
    request_info = request.form
    #Incoming data is processed here and converted into following format:
    data = [{'name': 'bill', 'state': 'CA', 'id': 012345},
            {'name': 'cindy', 'state': 'NY', 'id': 098765}, ...]
    return jsonify(data)

index.html:

<script type="text/javascript" src="{{ url_for('static'), filename='/js/script.js'}}"></script>
<form action="{{ url_for('table_data') }}" class="form-inline" method="post"
        role="form" enctype="application/json">
    <input type="text" class="form-control" id="name" name="name">
    <input type="text" class="form-control" id="state" name="state">
    <input type="text" class="form-control" id="id" name="id">
    <button type='submit' class="btn btn-default">Submit</button>
</form>
<p id="response"></p>

script.js:

$(document).ready(function() {
    $('form').on('submit', function(event) {
        $.ajax({
            url: '/table_data',
            data: $('form').serializeArray(),
            type: 'POST',
            success: function(response) {
                $('#response').text(response);
            }
        })
    });
});

I expect the returned JSON object to be printed to the screen underneath the form, but instead, the data returned is printed directly to the browser window, which doesn't maintain the structure of 'index.html' (which has navbars and a form). I am returned this:

[
    {
        'name': 'bill',
        'state': 'CA',
        'id': 012345
    },
    {
        'name': 'cindy',
        'state': 'NY',
        'id': 098765
    },
    ...
]

Again, this is the proper format, but the data isn't printing to the data

like I want it to. Brand new to JavaScript and jQuery/AJAX, so I'm fairly sure I'm missing something pretty trivial.

nat5142
  • 485
  • 9
  • 21
  • 1
    You are not preventing the default action of the form submission. The user submits the form and the browser sends the request and loads that page. – Patrick Evans Jul 01 '17 at 18:43
  • See [Ajax Form submit with preventDefault](https://stackoverflow.com/questions/20352799/ajax-form-submit-with-preventdefault). – krassowski Jul 01 '17 at 18:56
  • @PatrickEvans I tried adding "event.preventDefault();" under the "})" .ajax close, but nothing changed – nat5142 Jul 01 '17 at 19:03
  • It should work. Make sure that you include your script properly (can you open link generated by `{{ url_for('static'), filename='/js/script.js'}}` in your browser?). – krassowski Jul 01 '17 at 20:01

1 Answers1

2

SOLUTION:

Turns out I had quite a few issues going on. First, in a line I didn't include in the OP, my load of jQuery was bad. Not sure why, but I opened my console and saw the JS error (using Chrome, right click >> inspect >> "Console" tab at top right of page). I changed this from what I had (src="{{ url_for('static', filename="/js/jquery-3.2.1.min.js) }}" ) and instead just loaded it as a google hosted library:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

My response was then printed in the paragraph id="repsonse", but as:

[object, Object], [object, Object], ..., [object, Object]

To actually print the contents of the JSON object, I changed the line

$('#response').text(response);

to:

$('#response').text(JSON.stringify(response));

That printed my JSON objects with their contents to a paragraph on the page.

nat5142
  • 485
  • 9
  • 21