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

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.

Related

AEM multifield data-sly-repeat ${item} not working

This has been driving me nuts - hoping someone can help me.
I have a multifield component called 'books' with a single textfield: 'title'.
Everything seems to be working; the dialog box contains the multifield then I add two title fields then enter 'title1' and 'title2'.
then in the HTML itself I go:
<div data-sly-repeat="${properties.books}">
<p>${item}</p>
<p>${itemList.index</p>
<p>${item.title}</p>
</div>
What I don't get is, ${item} correctly gives me:
{"title": "title1"} {"title": "title2"}
and ${itemList.index} correctly gives me: 0 1
but ${item.title} keeps coming up blank. I also tried ${item["title"]} and that comes up blank too.
What am I doing wrong here? In my desperation I contemplated using
<div data-title="${item}"></div>
and then using JS to process the JSON object but I don't really want to do that.
Someone help, please!
It looks like your books property is either a JSON array string or a multivalued property with each value being a JSON object string;
The easiest way to parse the property is via a JS model like the following:
You could simplify this script to match your specific case, I made it general to multi-value and non-multi-value string properties.
/path/to/your-component/model.js:
"use strict";
use(function () {
// parse a JSON string property, including multivalued, returned as array
function parseJson(prop){
if(!prop) return [];
var result =[];
if(prop.constructor === Array){
prop.forEach(function(item){
result.push(JSON.parse(item));
});
}
else {
var parsed = JSON.parse(prop);
if(parsed.constructor === Array){
result = parsed;
}
else result = [parsed];
}
return result;
}
var $books = properties.get("books", java.lang.reflect.Array.newInstance(java.lang.String, 1));
var books = parseJson($books);
return {
books: books
}
});
/path/to/your-component/your-component.html:
<sly data-sly-use.model="model.js"/>
<div data-sly-repeat="${model.books}">
<p>${item}</p>
<p>${itemList.index</p>
<p>${item.title}</p>
</div>

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);
%>

Using Meteor what is the JS equivelent of {{{member}}}

I have a meteor helper that uses a reactive variable in a find to get a unique document using an id. My item button template looks like this:
<template name = "itemButton" >
<div class = "itemButton" name = {{_id}}>
{{{title}}}
</div>
</template>
using a reactive variable:
Template.landing.onCreated(function _OnCreated() {
this.f = new ReactiveVar();
this.f.set(false);
const handle = Meteor.subscribe("Feed");
});
now I have a method in a template several itemButton.
Template.landing.events({
'click .itemButton' : function(event, template){
alert(event.target.name);
template.f.set(event.target.name);
}
});
and I would like to use that name in a helper that would use this value as the _id.
Template.landing.helpers({
"GetFocus": function(){
alert(Template.instance().f.get()); // alerts undefined...
return(items.find({'_id':Template.instance().f.get()}));
}
});
So where I expect GetFocus to give me the document that generated the button I don't seem to be so lucky. Let me know if I can provide any additional clarification, and as always your input is appreciated.
Where I have template.f.set(event.target.name); I needed template.f.set(event.currentTarget.getAttribute('data-id')); where the html uses data-id instead of name.

Flask request not returning any info from select

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();
});
});

approach for validated form controls in AngularJS

My teammates and I are learning AngularJS, and are currently trying to do some simple form field validation. We realize there are many ways to do this, and we have tried
putting input through validation filters
using a combination of controller and validating service/factory
a validation directive on the input element
a directive comprising the label, input and error output elements
To me, the directive approach seems the most "correct". With #3, we ran into the issue of having to communicate the validation result to the error element (a span sibling). It's simple enough to do some scope juggling, but it seemed "more correct" to put the span in the directive, too, and bundle the whole form control. We ran into a couple of issue, and I would like the StackOverflow community's input on our solution and/or to clarify any misunderstandings.
var PATTERN_NAME = /^[- A-Za-z]{1,30}$/;
module.directive("inputName", [
function () {
return {
restrict: "E",
require: "ngModel",
scope: {
fieldName: "#",
modelName: "=",
labelName: "#",
focus: "#"
},
template: '<div>' +
'<label for="{{fieldName}}">{{labelName}}</label>' +
'<input type="text" ng-model="modelName" id="{{fieldName}}" name="{{fieldName}}" placeholder="{{labelName}}" x-blur="validateName()" ng-change="validateName()" required>' +
'<span class="inputError" ng-show="errorCode">{{ errorCode | errorMsgFltr }}</span>' +
'</div>',
link: function (scope, elem, attrs, ngModel)
{
var errorCode = "";
if (scope.focus == 'yes') {
// set focus
}
scope.validateName = function () {
if (scope.modelName == undefined || scope.modelName == "" || scope.modelName == null) {
scope.errorCode = 10000;
ngModel.$setValidity("name", false);
} else if (! PATTERN_NAME.test(scope.modelName)) {
scope.errorCode = 10001;
ngModel.$setValidity("name", false);
} else {
scope.errorCode = "";
ngModel.$setValidity("name", true);
}
};
}
};
}
]);
used as
<form novalidate name="addUser">
<x-input-name
label-name="First Name"
field-name="firstName"
ng-model="firstName"
focus="yes"
model-name="user.firstName">
</x-input-name>
<x-input-name
label-name="Last Name"
field-name="lastName"
ng-model="lastName"
model-name="user.lastName">
</x-input-name>
...
</form>
First, because both form and input are overridden by AngularJS directives, we needed access to the ngModel API (ngModelController) to allow the now-nested input to be able to communicate validity to the parent FormController. Thus, we had to require: "ngModel", which becomes the ngModel option to the link function.
Secondly, even though fieldName and ngModel are given the same value, we had to use them separately. The one-way-bound (1WB) fieldName is used as an attribute value. We found that we couldn't use the curly braces in an ngModel directive. Further, we couldn't use a 1WB input with ngModel and we couldn't use a two-way-bound (2WB) input with values that should be static. If we use a single, 2WB input, the model works, but attributes like id and name become the values given to the form control.
Finally, because we are sometimes reusing the directive in the same form (e.g., first name and last name), we had to make attributes like focus parameters to be passed in.
Personally, I would also like to see the onblur and onchange events bound using JavaScript in the link function, but I'm not sure how to access the template markup from within link, especially outside/ignorant of the larger DOM.