Flask request not returning any info from select - forms

I'm trying to set up a simple select dropdown form with Flask. Based on the option chosen, I grab different data from my database, and display it back into a div on my html template. But I can't seem to get the Flask request to register any of the select options. When I print request.form or request.args, I always get empty Dicts. It's probably something simple I'm missing but I can't seem to find the problem. I've gotten this to work with several input and button forms, but I can't get it to work right for selects.
Here is a bit of my html template code, with the form and select. I've tried both GET and POST method in the form.
<div class="options" id="options">
<form class="form-horizontal container-fluid" role="form" method="GET" action="exploresn2.html">
<div class="form-group">
<label for="xaxis" class="col-sm-2 control-label">X-axis:</label>
<div class="col-sm-2">
<select name="xaxis" class="form-control" id="xaxis">
<option selected value="mjd" id="mjd">MJD</option>
<option value="seeing" id="seeing">Seeing</option>
<option value="airmass" id="airmass">Airmass</option>
<option value="hourangle" id="hourangle">Hour Angle</option>
</select>
</div>
</div>
</form>
</div>
In Flask, at first, I tried inside my app
import flask
from flask import request, render_template, send_from_directory, current_app
explore_page = flask.Blueprint("explore_page", __name__)
#explore_page.route('/exploresn2.html', methods=['GET','POST'])
def explore():
xaxis = str(request.args.get("xaxis", "any"))
.... [populate new xaxis variable based on request option selected]
exploreDict['xaxis'] = xaxis
return render_template("exploresn2.html", **exploreDict)
or
mjd = valueFromRequest(key='mjd', request=request, default=None)
if mjd:
mjds = [int(exp.platedbExposure.start_time/(24*3600)) for exp in exposures]
xaxis = mjds
exploreDict['xaxis'] = xaxis
to look for and grab a specific values, or in the first case, any value select. The valueFromRequest is function that grabs data from either GET or POST requests.
but this returns nothing, and then I tried just printing the entire request.args (or request.form) and it returns and empty Dict. Everything I try it still returns empty Dicts. So I'm missing some set up somewhere I think but the form looks right to me?

I'm not sure if this is the actual answer to this problem that I was looking for, but here is what I came up with. I couldn't actually get the Flask to accept a GET request into the original explore method defined, so I implemented a new method in Flask to return a JSON object
#explore_page.route('/getdata', methods=['GET','POST'])
def getData(name=None):
name = str(request.args.get("xaxis", "mjd"))
xaxis = 'populate new xaxis data based on value of name'
data = '(x,y) data array filled with values for plotting'
axisrange = range of x,y data for axes for plot
return jsonify(result=data, range=axisrange)
and then I just made a GET request via javascript to that method whenever the select button changes. So in my exploresn2.html template I have (using Flot for plotting)
$("#xaxis").change(function(){
var newname = $("#xaxis :selected").text();
var axes = plot.getAxes();
options = plot.getOptions();
var plotdata = plot.getData();
// make a GET request and return new data
$.getJSON($SCRIPT_ROOT + '/getdata', {'xaxis':$("#xaxis :selected").val()},
function(newdata){
// set new data
for (var i = 0; i < plotdata.length; ++i) {
plotdata[i].data = newdata.result[plotdata[i].label];
}
// set new axes
axes.xaxis.options.panRange = [newdata.range[0]-50,newdata.range[1]+50];
axes.xaxis.options.axisLabel = newname;
axes.xaxis.options.min = newdata.range[0]-1;
axes.xaxis.options.max = newdata.range[1]+1;
axes.yaxis.options.min = newdata.range[2];
axes.yaxis.options.max = newdata.range[3];
// redraw plot
plot.setData(plotdata);
plot.setupGrid();
plot.draw();
});
});

Related

JAX-RS, #FormParam display result in the same page

I have this program that I am coding, the main thing is mostly to get familiar with Jax-rs and rest API. I am sending from a form in JSP page one input and with POST I pass it to my java Response class(that I use annotation #FormParam), it does what calculation I need and then I get the result in another link, what can i do to take the result just below my button on the same page? For my button function I use javascript, and when I push it I don't want to be redirected and take the result like this.
So i use this form and a javascript function in my jsp to pass the value in my POST method in java throw #FormParam
<form name="Form1" method="post">
<p>
Name : <input type="text" name="malename" id="malename" autofocus
value="enter your name..." />
</p>
<input type="submit" name="action" id="malename" value="I'm feeling lucky"
onclick="OnButton1();"> </form>
function OnButton1() {
document.Form1.action = "webapi/perfectmatcher/mate"
document.Form1.target = "_self"; // Open in a new window
document.Form1.submit(); // Submit the page
//return;
}
Here after i have the value i use two other classes to do the calculations and return the result i need. In a few words i pass a value in my form and when i push the button i am redirected in another link(the path of POST) and i display the result. I want to display the result below my button. I hope the code is helpful and i hope i am clear with my explanation
#POST
#Path("/mate")
#Produces(MediaType.TEXT_PLAIN)
public Response postMaleName(#FormParam("malename") String malename) {
String femalename = NumMatcher.numMatcher(Numberizer.numberizer(malename));
// FemaleName female = new FemaleName(femalename);
female.setName(femalename);
System.out.println(female.getName());
return Response.status(200).entity("Perfect Match for " + malename + " is " + femalename).build();
}
P.S.:The object female that i am trying to create its for testing purposes, i was trying somehow to get the information that i store but i cannot find how!!I used even jsp expressions but i get null value of course ...
<%
FemaleName female = new FemaleName("john");
String string = female.getName();
out.print(string);
%>

Angularfire: How to Filter with a Specific key or ID

So here is my quick code.
var thisisformykeyorid =$scope.id;
var ref = firebase.database().ref('/myusers/').child("users");
$scope.users= $firebaseArray(ref);
var query = ref.orderByChild("timestamp").limitToLast(100);
$scope.filteruser= $firebaseArray(query);
In my HTML is
<div ng-repeat="samplein filteruser>
<h2>{{ sample.firstname}}</h2>
<p>{{ sample.age}}</p>
</div>
So in firebase there are unique id or keys for each set of data.
How do i add a filter or query to select a set of data from firebase using my variable ? (assuming $scope.id is a unique key) Please be guided that i dont want to use ng-repeat anymore because i only want to view only 1 set of data. Need help
If you know what object you want to display, you can use $firebaseObject instead of $firebaseArray:
var ref = firebase.database().ref('/myusers/').child("users");
$scope.user = $firebaseObject(ref.child($scope.id));
And then display it in your HTML with:
<div >
<h2>{{user.firstname}}</h2>
<p>{{user.age}}</p>
</div>

How to serialize html form in dart as a string for submission

In jQuery, there is a function to serialize a form element so for example I can submit it as an ajax request.
Let's say we have a form such as this:
<form id="form">
<select name="single">
<option>Single</option>
<option selected="selected">Single2</option>
</select>
<input type="checkbox" name="check" value="check1" id="ch1">
<input name="otherName" value="textValue" type="text">
</form>
If I do this with the help of jquery
var str = $( "form" ).serialize();
console.log(str);
the result would be
single=Single2&check=check1&otherName=textValue
Is there such functionality in dart's FormElement or I have to code it myself? Thanks.
I came up with my own simple solution that might not work in all cases (but for me it is workikng). The procedure is this:
First we need to extract all input or select element names and values from the form into Dart's Map, so the element name will be the key and value the value (e.g. {'single': 'Single2'}).
Then we will loop through this Map and manually create the resulting string.
The code might look something like this:
FormElement form = querySelector('#my-form'); // To select the form
Map data = {};
// Form elements to extract {name: value} from
final formElementSelectors = "select, input";
form.querySelectorAll(formElementSelectors).forEach((SelectElement el) {
data[el.name] = el.value;
});
var parameters = "";
for (var key in data.keys) {
if (parameters.isNotEmpty) {
parameters += "&";
}
parameters += '$key=${data[key]}';
}
Parameters should now contain all the {name: value} pairs from the specified form.
I haven't seen anything like that yet.
In this example Seth Ladd uses Polymers template to assign the form field values to a class which get's serialized.

Form Validation: Select

I'm trying to display an error message if the select button in my form is not changed. It works fine for the rest but not the select, please help! and I know that the image wont work like that, I cant post images as a new member.
Html is:
<div id='first_name_error' class='error'><image code here></div>
<div><input type='text' name='first_name' id='first_name' placeholder="YOUR FIRST NAME*"></div>
Number of Guests:*<div id='guests_error' class='error'><img src='img/booking/error.png'></div>
<div><select name='guests' id='guests' style="margin:0px;" SIZE="1"><OPTION SELECTED value="guests">Guests<OPTION>2<OPTION>3<OPTION>4</SELECT></div>
Code Is
var error = false;
var first_name = $('#first_name').val();
var second_name = $('#second_name').val();
var email = $('#email').val();
var number = $('#number').val();
var guests = $('#guests').val();
var message = $('#message').val();
if(first_name.length == 0){var error = true;$('#first_name_error').fadeIn(500);}else{$('#first_name_error').fadeOut(500);}
if(guests.value == Guests){var error = true;$('#guests_error').fadeIn(500);}else{$('#guests_error').fadeOut(500);}
Notice that your "guests" variable is already set to the value of the select element (using jQuery val()). There is no need to attempt to access the "value" property of the "guests" variable.
Second, the comparison you are making is to the identifier Guests, not to the string "Guests". You'll want to put quotes around that to make it a string literal.
You can see an example of this here: http://jsfiddle.net/tbuCJ/

Get all values from drop-down

I'm trying to find a way to get all values and label from drop-down in web page.
With label, I could use:
my #labels = $sel->get_select_options('s');
Return value is array of label in drop-down.
However, there's no equivalent method for getting all values.
Do you guys know how to do this?
As far as in Selenium 1 there is no direct API for this. However you could try this.
Consider a <select> like below.
<select name="mydropdown" id="optionset">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
Below is the snippet in Java to retrieve values. You can get the logic from this snippet and implement it in Perl.
int no_of_options = selenium.getSelectOptions("//select[#id='optionset']").length
String option_values[] = new String[no_of_options];
for (int i=0;i<no_of_options;i++){
String value = selenium.getAttribute("//select[#id='optionset']/option["+i+"]/#value");
option_values[i] = value;
}
Hope this helps.