0

I have a dropdown that I am using. Here is the HTML:

  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  <script src="{{url_for('static',filename='dropdown_change.js')}}"></script>


 <form action="{{url_for('select_ID')}}" method="POST">
  <label for="input_ID">ID</label>
  <input type="text" />
  <label for="Node_Type">Node_Type</label>
  <select id="dropdown_change">
    <option value=1>Customer</option>
    <option value=2>Phone</option>
    <option value=3>ID_Card</option>
  </select>
<input type='submit' value='Submit'>
</form>

Here is my flask view:

import db_connect_test
from db_connect_test import Viz_Connector
from flask import Flask, request, session, redirect, url_for, render_template, flash,json,jsonify
import os
app = Flask(__name__)
@app.route('/',methods = ['GET','POST'])
def select_ID():
    if request.method == 'POST':
        ID=request.form['input_ID']
        Node_Type = request.form['Node_Type']
        data = Viz_Connector(ID,Node_type).get_data()
        return  render_template('dropdown.html',data=json.dumps(data))


    return render_template('dropdown.html')

if __name__ == '__main__':
    host = os.getenv('IP','0.0.0.0')
    port = int(os.getenv('PORT',5000))
    app.secret_key = os.urandom(24)
    app.run(host=host,port=port)

Here is my jquery for the drop down. There is a event listenere for "clicking" of the submit button. I think the way I am hand

    $('input[type=submit]').click(function() {
   var ID = $("#input_ID").val();
   var selectID = $("#dropdown_change").val();
   $.ajax({
     type: "POST",
     url: "/select_ID",

     data: {
       ID: ID,
       Node_Type: selectID  //right way to pass the data to flask?
     },
     success: function(data) {
       alert('SUCCESS: ' + data);
     },
     error: function(xhr, textStatus, errorThrown) {
       document.getElementById('dropdown_change').selectedIndex = 0;
       showMsg('ERROR: ' + errorThrown);
       return false;
     }
   });
   return false;
 });

When I run this it fails with:

   400:Bad request
5
  • @lix URL corresponds to the "select_ID" function in flask. Commented Dec 9, 2016 at 19:16
  • 1
    I think you are missing #input_ID on the text input. Have you checked JS console for error? Commented Dec 9, 2016 at 19:18
  • You need to reconcile the variable names as well. The simplest way is to match up all of the HTML IDs to the posted form values. Commented Dec 9, 2016 at 19:32
  • @dana I think they are reconciled now and I did see something you posted in the answer section but it is gone now. Commented Dec 9, 2016 at 19:43
  • @optimus_prime - OK, I un-deleted my answer. You may have a couple additional things to cleanup, but pointed out at least a few issues. Commented Dec 9, 2016 at 19:47

2 Answers 2

1

You need to url-encode your data before sending it to the server. Also, your routing will not pickup a POST to the path /select_ID. You should be posting to / instead. A slightly slicker way to do this is to read the action attribute in jQuery.

HTML:

<form action="{{url_for('select_ID')}}" method="POST">
    <label for="input_ID">ID</label>
    <input id="input_ID" type="text" />
    <label for="Node_Type">Node_Type</label>
    <select id="Node_Type">
        <option value=1>Customer</option>
        <option value=2>Phone</option>
        <option value=3>ID_Card</option>
    </select>
    <input type='submit' value='Submit'>
</form>

JavaScript:

$('input[type=submit]').click(function() {
    var input_ID= $("#input_ID").val();
    var Node_Type= $("#Node_Type").val();
    $.ajax({
        type: "POST",
        url: $(this).closest("form").attr("action"), // read the URL from the form attribute
        data: $.param({ // use $.param() to convert from a JSON object to url-encoded
            input_ID: input_ID,
            Node_Type: Node_Type
        }),
        success: function(data) {
            alert('SUCCESS: ' + data);
        },
        error: function(xhr, textStatus, errorThrown) {
            document.getElementById('Node_Type').selectedIndex = 0;
            showMsg('ERROR: ' + errorThrown);
            return false;
        }
    });
    return false;
});

NOTE: Per my comment above, I reconciled the HTML IDs and JavaScript variables to use input_ID and Node_Type since this is what is expected on the server.

Sign up to request clarification or add additional context in comments.

7 Comments

Hi , it is not able to complete the "GET" request and fails with: BuildError: Could not build url for endpoint 'index'. Did you mean 'static' instead?
Hmmm... Maybe you want to leave in {{url_for('select_ID')}} after all, but leave the modified JavaScript code as is. I will update my answer.
So , now it does work but it goes to the url: 172.31.179.196:5000/form%20action= and gives a 404 NOT found. It should ideally connect with the back end db and render a graph. All I need to confirm is that is this a separate error related to the back end db or linked one?
The browser is redirected? That does not make any sense since the button click event is being cancelled and jQuery is being used to send the data to the server. I don't see any JavaScript redirects either. Have you tried inspecting the request using a tool like Fiddler? It might give you a better idea of what is actually being sent to the server and the response that is being generated.
Thanks a ton. got it to work. The problem was the placement of the <script type= "javascript"> tags.
|
0

Try changing your route:

@app.route('/',methods = ['GET','POST'])
def select_ID():

to

@app.route('/select_ID',methods = ['GET','POST'])
def select_ID():

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.