Reputation: 10624
I'm currently trying to create a simple form in Dart with simply a username and email for registration purposes.
I cannot find a complete working example that I can test. If someone can explain how to convert the jQuery code below to Dart, I think that would clarify things greatly.
Also I've seen the FormData
class for Dart but no examples. Any help is appreciated.
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#responseDiv").empty();
$("#responseDiv").html(info);
});
$("#myForm").submit( function() {
return false;
});
});
Upvotes: 7
Views: 1142
Reputation: 30312
First import the two libraries:
import 'dart:html';
import 'dart:convert';
Then we define a serializer function:
serializeForm(FormElement form) {
var data = {};
// Build data object.
form.querySelectorAll('input,select').forEach((Element el) {
if (el is InputElement)
data[el.name] = el.value;
});
return data;
}
It simply serializes a form into a Map
of data. I am not aware of a Dart form serializer, there may be some package for that purpose. Note that the above example only deals with inputs.
Next we assume the following HTML:
<form id="myForm" action="/bar">
<label>Foo:</label>
<input type="text" name="foo" value="bar" />
</form>
<button id="mySubmit">Send it</button>
And last our Dart client-side code for form handling:
main() {
FormElement form = querySelector('#myForm');
ButtonElement button = querySelector('#mySubmit');
button.onClick.listen((e) {
var req = new HttpRequest();
req.onReadyStateChange.listen((ProgressEvent e) {
if (req.readyState == HttpRequest.DONE) {
print('Data submitted!');
}
});
req.open('POST', form.action);
req.send(JSON.encode(serializeForm(form)));
});
}
This should get you started.
You might also want to use Polymer for your forms.
Upvotes: 11
Reputation: 39
Working off the above example. You could do something like this also.
main(){
var form = new FormData(query('#myForm');
var button = query('#mySubmit');
button.onClick.listen((e){
var request = new HttpRequest();
request.on.readyStateChange.add((HttpRequestProgressEvent e) {
if (request.readyState == HttpRequest.DONE) {
print('Data submitted!');
}
});
request.open('POST','http://localhost/form_info.php');
request.send(form);
});
}
Upvotes: 0