Get data from html and and pass the data back to the front end using ajax or js

You can use ajax with Jquery. You can see this doc for more details.

How to proceed:

  1. Configure js scripts

In your HTML file template:

  • Load Jquery:

Load Jquery preferably before any other javascript files.

Either statically:

<script type=text/javascript src="https://stackoverflow.com/questions/52870184/{{url_for("static', filename="jquery.js") }}"> </script>

Or using Google’s AJAX Libraries API:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="https://stackoverflow.com/questions/52870184/{{url_for("static', filename="jquery.js") }}">\x3C/script>')</script>
  • Add a dynamic path to the site:

    <script type=text/javascript>$SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; </script>
    

    This script tag sets a global variable to the prefix to the root of the application.

    1. On the side of Flask

Write a function that will take as argument the value entered in the form by the user, perform search operations and return a JSON object with the list you want to display.

@app.route("/_signUp")
def signUp():
    myString = request.args.get('myString')

    """couple of find and search operations the output of which is in 
    this dropdown_list list"""

    dropdown_list = ['A', 'B', 'C'] #sample

    return jsonify(dropdown_list=dropdown_list)
  1. Back in the HTML code

Write a script that will retrieve the data entered, send them in Ajax to the server and display the information returned by the server.

<script type=text/javascript>
    $(function(){
        $('#btnSignUp').bind('click', function(){
            $.getJSON($SCRIPT_ROOT + '/_signUp', {
                myString: $('input[name="Nitro"]').val(),
            },function(data){
                $('#info').append('<li>' + data.dropdown_list[0] + '</li>' );//A
                $('#info').append('<li>' + data.dropdown_list[1] + '</li>' );//B
                $('#info').append('<li>' + data.dropdown_list[2] + '</li>' );//C
            }
        });
    });
</script>
<div id='nitroo'>
    Nitro_search: <input type="text" placeholder="Apply Nitro" name="Nitro" id="Nitro">
    <button id="btnSignUp" class="btn btn-lg btn-primary btn-block" type="button">Search</button>
   <pre id="info"></pre>
</div>

See this link for more details.

Leave a Comment