0

I am trying to get data from webpage to my flask app and after a few operations on it,the output list im trying to send it back to front end as a dropdown list.

What i have done till now:

there is a user form where the user enters details and clicks on submit and he gets a json output.

in this form,I have a search button which when the user inputs a string,that string is sent to the flask app route and few search operations are done and outputs a list of items(TILL this part it is working!)

What i need to get to work is the output list should again be sent back to the form page which i have trouble getting it to work.

This is what i have done so far:

    var successFunction = function(response) {
     /* do something here */
            $('#info').html(JSON.stringify(data, null, '   '));
    });
}
$(function(){
        $('#btnSignUp').click(function(){

                $.ajax({
                        url: '/signUp',
                        data: $('form').serialize(),
                        type: 'POST',
                        success: successfunction(response)
                        error: function(error){
                                console.log(error);
                        }
                });
        });
});

the flask app has something like this:

from flask import Flask, render_template, request,jsonify,url_for
import json,os,re
app = Flask(__name__)

@app.route('/',methods=['GET','POST'])
def form():
        if request.method == 'POST': #this block is only entered when the form is submitted
                result = { key: value[0] if len(value) == 1 else value
                      for key, value in request.form.iterlists()
                        }
                return json.dumps(result,indent=2)
        return render_template('form_backup1.html')


@app.route("/signUp", methods=["POST","GET"])
def signUp():
        jsdata = request.form['Nitro']
        <couple of find and search operations the output of which is in 
        this dropdown_list list>
        return jsonify(dropdown_list)

if __name__ == '__main__':
   app.run(host="0.0.0.0",port="5000",debug = True)

snipped html page just to show the search box:

      <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>

As I said I am able to get the text entered by the user in the html form when he clicks on search. the output lists from python is where I am having trouble of getting to front end.

Any help on this would be much appreciated.

Thanks

  • 1
    having trouble means what exactly? You've got a bug or error? You don't know what code to write? It's not clear what the problem is. Is python outputting the right data? Is it not presented in the way you wanted? Please be specific about your issue. Thanks – ADyson Oct 18 '18 at 09:15
  • Python is outputting the list correctly.I am having trouble getting the list to the front end web page.the web page displays blank when i click on Search button. – Carmel Jacob Oct 18 '18 at 09:21
  • any errors in your browser console? BTW in `var successFunction = function(response) { /* do something here */ $('#info').html(JSON.stringify(data, null, ' ')); });`...the variable called `data` is not defined. Perhaps you meant to use `response` instead, since that's the name you've given to the variable containing the data provided by the server – ADyson Oct 18 '18 at 09:32
  • The browser console shows the list what I need.but I am not seeing it on browser itself.Is my approach correct? Using Ajax to get the information back from Python script? – Carmel Jacob Oct 18 '18 at 09:37
  • That's what you I mean, I think you should probably change your code to `$('#info').html(JSON.stringify(response, null, ' '));`. Your approach is fine (at least from the JavaScript side, I don't know any python, but I'll take your word that it's working...), I just think you're reading from the wrong variable. – ADyson Oct 18 '18 at 09:39

1 Answers1

1

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="{{url_for('static', filename='jquery.js') }}"> </script>

Or using Google’s AJAX Libraries API:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{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.

Tobin
  • 2,029
  • 2
  • 11
  • 19
  • Thanks!!!!This was exactly what i needed worked wonderfully,I made the list to a dropdown list. Just one more query,every time i click on Search button in the form it output a dropdown list of items,the next time i try a different search,the drop down list gets appended with the previous and the new items.Any idea on how to only let the drop down list contain the latest items based on the last search given – Carmel Jacob Oct 22 '18 at 09:58
  • @CarmelJacob you can use the jquery **.remove()** function (to remove all the elements under the **
  • ** tag in your **
    ** tag) and then add the new search results. Try this:  `$('#info li').remove( ); `  `$('#info').append('
  • ' + data.dropdown_list[0] + '
  • ' );//A `... Also jQuery provides many functions for manipulating elements and content on a page, from simply replacing HTML, to completely removing tags and content from the page. Check out [this list](https://api.jquery.com/category/manipulation/) of jquery functions for more info. – Tobin Oct 22 '18 at 11:28
  • `$.getJSON($SCRIPT_ROOT + '/_signUp', { myString: $('input[name="Nitro"]').val(), },function(data){ $.each(data.dropdown_list,function(index,value) { $('#sel').remove(); $('#sel').append(''); }); }); ` @Tobin When i click on search button,the dropdown list gets removed and new one doesnt get added – Carmel Jacob Oct 23 '18 at 06:25
  • It does not work because the target tag **#sel** no longer exists when you add your list. The structure of the code must be taken into account (look at my previous comment) ... Suppose you have an **
      ** tag followed by a series of **
    • ** tags. What you want to delete is not all the **
        ** tag, but the **
      • ** tags. Then inside the **
          ** tag you add your new list with new **
        • ** tags. In this case in your jquery code you will select all the **
        • ** tags, remove them and add new **
        • ** tags in your **
            ** tag which is the target.. Look at my next comment.
    – Tobin Oct 23 '18 at 14:46
  • Your code should look like this : `$.getJSON($SCRIPT_ROOT + '/_signUp', { myString: $('input[name="Nitro"]').val(), },function(data){ $('#sel option').remove(); $.each(data.dropdown_list,function(index,value) { $('#sel').append(''); }); }); `... Assuming that the id #sel refers to a div tag (or other), which contains a series of ** – Tobin Oct 23 '18 at 15:03