GWT - how do I send the form asynchronously? - java

I am adding a file upload functionality to an application.
I'm following some tutorials, so far I get something like this:
final FormPanel form = new FormPanel();
form.setAction(GWT.getModuleBaseURL() + "fileupload");
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
final FileUpload fileUpload = new FileUpload();
submit.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
String filename = fileUpload.getFilename();
if (filename.length() == 0) {
} else {
form.submit();
}
}
});
I've made the fileupload servlet, and I guess it's okay. The problem is, after the form.submit() the page gets reloaded, but I would like to send it asynchronously instead.
Something like that is dead simple in php and jquery.
Could anybody help?
Best regards.

For submitting arbitrary data (objects) use GWT-RPC. For file upload take a look at gwtupload.

Related

Form Submit Action

I'm new to Android. I have one application in which I'm planning to add App Rate function. I found below library for it
Apprate Library
final RatingDialog ratingDialog = new RatingDialog.Builder(this)
.threshold(3)
.session(7)
.onRatingBarFormSumbit(new RatingDialog.RatingDialogFormListener() {
#Override
public void onFormSubmitted(String feedback) {
}
}).build();
ratingDialog.show();
I have impemented it but there is nothing written for feedback email related code. Can some one please tell me where I should write my email so when user can submit feedback? Can I get an email?
Thanks!
Any action after submit would be done inside:
public void onFormSubmitted(String feedback) {
// put the code here
}

Uploading Files through GWT-RPC?

Uploading files with GWT is usually done with a FileUpload inside a FormPanel like this:
// Create a FormPanel and point it at a service.
final FormPanel form = new FormPanel();
form.setAction("/myFormHandler");
// Because we're going to add a FileUpload widget, we'll need to set the
// form to use the POST method, and multipart MIME encoding.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// Create a panel to hold all of the form widgets.
VerticalPanel panel = new VerticalPanel();
form.setWidget(panel);
// Create a TextBox, giving it a name so that it will be submitted.
final TextBox tb = new TextBox();
tb.setName("textBoxFormElement");
panel.add(tb);
// Create a ListBox, giving it a name and some values to be associated with
// its options.
ListBox lb = new ListBox();
lb.setName("listBoxFormElement");
lb.addItem("foo", "fooValue");
lb.addItem("bar", "barValue");
lb.addItem("baz", "bazValue");
panel.add(lb);
// Create a FileUpload widget.
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
panel.add(upload);
// Add a 'submit' button.
panel.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
form.submit();
}
}));
Are there any other ways to handle file upload with GWT? Is it possible to do in with GWT-RPC or REST?
Edit: Browser requirement is Only Webkit
With modern browsers you can get the raw bytes of the input type=file (in a base64 data url). Having the bytes you can send them whatever the way you like.
Here's some code, displaying a file input dialog and getting the raw bytes (dataURL):
class Util {
static native void info (Object obj) /*-{
if ($wnd.console && $wnd.console.log) $wnd.console.log (obj)
}-*/;
/** Fires a "click" event on an HTML element. */
public static native void click (final JavaScriptObject element) /*-{
if (element.click) element.click();
}-*/;
/** Read a file from the local filesystem. The file should have been choosen via an `input type=file`.
* See also: http://www.html5rocks.com/ru/tutorials/file/dndfiles/; http://www.w3.org/TR/FileAPI/ */
public static native void readFile (JavaScriptObject inputFile, V1<String> andThen) /*-{
var files = inputFile.files
if ($wnd.console) $wnd.console.log ('readFile; input: ', inputFile, files)
if (!files || !files.length) return
var reader = new FileReader()
reader.onload = function (progressEvent) {
//$wnd.console.log ('read event: ', progressEvent, 'read: ', reader.result)
andThen.#client.Closure.V1::call(Ljava/lang/Object;)(reader.result)
}
reader.readAsDataURL (files[0])
}-*/;
}
// Remove old form.
final Element oldForm = Document.get().getElementById ("uploadForm");
if (oldForm != null) oldForm.getParentNode().removeChild (oldForm);
// A hidden form used to upload the files.
final FormPanel form = new FormPanel();
form.getElement().setId ("uploadForm");
final Style formStyle = form.getElement().getStyle();
formStyle.setDisplay (Display.INLINE_BLOCK); formStyle.setOverflow (Overflow.HIDDEN); formStyle.setWidth (0, Unit.PX); formStyle.setHeight (0, Unit.PX);
form.setAction ("http://.../");
form.setEncoding (FormPanel.ENCODING_MULTIPART); form.setMethod (FormPanel.METHOD_POST);
final FileUpload upload = new FileUpload(); upload.setName ("image");
form.add (upload);
RootPanel.get().add (form);
upload.addChangeHandler (new ChangeHandler() {public void onChange (final ChangeEvent event) {
Util.info ("Loading: " + upload.getFilename());
Util.readFile (upload.getElement(), new V1<String>() {public void call (final String dataURL) {
Util.info ("Loaded: " + upload.getFilename() + " (url is " + dataURL.length() + " bytes)");
}});
}});
// Trigger the upload dialogue. See also: http://aspalliance.com/articleViewer.aspx?aId=1441&pId=-1
Util.click (upload.getElement());

GWT FileUpload with Progress Listener

I want to observe the upload percentage of a file upload from GWT.
In JavaScript you can use a XMLHttpRequest and add an event listener like this:
var oReq = new XMLHttpRequest();
oReq.upload.addEventListener("progress", updateProgress, false);
// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
// ...
} else {
// Unable to compute progress information since the total size is unknown
}
}
(The above code is from here.)
This is also done very easily in jQuery as:
var $request = $.ajax({
xhr: function() {
xhrNativeObject = new window.XMLHttpRequest();
//Upload progress
xhrNativeObject.upload.addEventListener("progress", function(event) { ... }
}
});
I want to do the same with GWT. I could use a RequestBuilder to send a request, but this is only a high level wrapper around the XMLHttpRequest JavaScriot object. Another possibility would be to use the GWT XMLHttpRequest class which is a JSNI wrapper of the JavaScript XMLHttpRequest.
My problem:
How can I add a progress listener to the XMLHttpRequest or the RequestBuilder?
I used before gwt-upload library.
You dont need to rediscover America.
Thanks for moxie group
gwt-upload-project page
//upload spring service conroller
#RequestBody public void uploadImage(#RequestParam("file") MultipartFile file ){
//what ever you want
}
XML Configuration
<bean id=multipartResolver" class ="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
GWT Elemental contains all you need already AFAICT.

gwt form: request send and arrived, but no response in gwt

I must be missing something simple, but I'm stuck.
I created a FormPanel in gwt that, according to firebug sends the request.
the link works, as I copied the requestlink from firebug and tried it natively in a browser window.
Yes, client and server host are the same --> localhost.
But the answer doesn't arrive at gwt. Not even the client browser - firebug shows no result eighter.
This is my little form:
Button form = new Button ("SendForm", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
logger.log(Level.FINER, "Creating SubmitForm...");
TextBox cmd = new TextBox();
cmd.setName("cmd");
cmd.setText("GetMenuitemList");
Button sendbutton = new Button("Senden");
logger.log(Level.FINEST, "Creating grid...");
Grid grid = new Grid(1, 2);
grid.setWidget(0, 0, new Label("Command"));
grid.setWidget(0, 1, cmd);
VerticalPanel vPan = new VerticalPanel();
//vPan.add(grid);
vPan.add(sendbutton);
logger.log(Level.FINEST, "Creating FormPanel...");
final FormPanel formPan = new FormPanel();
formPan.setMethod(FormPanel.METHOD_POST);
formPan.setAction(RequestHelper.getLink("Menu.php"));
logger.log(Level.FINEST, "Binding Send button...");
logger.log(Level.FINEST, "Binding SubmitHandler...");
formPan.addSubmitHandler(new SubmitHandler() {
#Override
public void onSubmit(SubmitEvent event) {
OptionPane.showMessageDialog("Form submit", event.toDebugString(), MessageType.INFO, true);
}
});
logger.log(Level.FINEST, "Binding SubmitCompleteHandler...");
formPan.addSubmitCompleteHandler(new SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
OptionPane.showMessageDialog("Form SubmitComplete", event.toDebugString(), MessageType.INFO, true);
}
});
logger.log(Level.FINEST, "Adding grid to formpan...");
formPan.add(grid);
formPan.add(vPan);
logger.log(Level.FINEST, "Creating DialogBox...");
final DialogBox box = OptionPane.createClosableBox("TestForm", true);
sendbutton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
formPan.submit();
box.hide();
}
});
box.add(formPan);
box.center();
}
});
The expected answer looks like this:
{"sessionid":"6dbqibo25e0bn46fldqh37psj5","data":[{"title":"Start","Controller":"Start","Action":"Index","tooltip":"Startseite, Begr\u00fc\u00dfung","prefetch":"1"},{"title":"Register","Controller":"Person","Action":"Index","tooltip":"Neue Benutzer registrieren","prefetch":"0"},{"title":"Daten","Controller":"Contact","Action":"Index","tooltip":"Die eigenen Daten bearbeiten","prefetch":"1"},{"title":"Teilnehmerlisten","Controller":"Lists","Action":"Index","tooltip":"Listen der registrierten Benutzer","prefetch":"0"},{"title":"Suche","Controller":"Search","Action":"Index","tooltip":"Namenssuche nach Benutzer mit Kontaktm\u00f6glichkeit","prefetch":"1"},{"title":"Kalender","Controller":"Calendar","Action":"Index","tooltip":"Termine","prefetch":"1"},{"title":"Newsletter","Controller":"Newsletter","Action":"Index","tooltip":"Verschicken von Newslettern","prefetch":"1"},{"title":"Wettk\u00e4mpfer","Controller":"Competitor","Action":"Index","tooltip":"Zugriff auf Wettk\u00e4mpfer","prefetch":"1"},{"title":"Upload","Controller":"Upload","Action":"Index","tooltip":"Bilder, Videos o.\u00e4. hochladen","prefetch":"0"},{"title":"Administration","Controller":"Admin","Action":"Index","tooltip":"Datenbankfunktionen und Benutzerrechte","prefetch":"1"}]}
So, what is going wrong here?
BTW, I'll use this technique for a login form. I read, its better to do this in a form than via RequestBuilder (that worked already). File upload will come later, so the form question needs an answer in any case...
Thank you in advance.
Markus
Edit: ok, I tested on Chromium, Konqueror and Opera also - the code works. It's just firefox. Ideas to get it going with firefox?
I'm a total newby in eclipse and gwt... maybe some compiler option?
I found and solved the problem myself: after the form.submit was executed, I hid the form Panel.
That is not allowed as javadoc says:
The FormPanel must not be detached (i.e. removed from its parent or otherwise disconnected from a RootPanel) until the submission is complete. Otherwise, notification of submission will fail.

Is it possible to nest forms in Wicket that are independent of each other?

Is it possible to nest forms in Wicket that are independent of each other? I want to have a form with a submit button and a cancel button. Both buttons should direct the user to the same page (let's call it Foo). The submit button should send some info to the server first; the cancel button should do nothing.
Here's a really simplified version of my existing code:
Form form = new Form() {
public void onSubmit()
{
PageParameters params = new PageParameters();
params.put("DocumentID", docID);
setResponsePage(Foo.class, params);
}
};
DropDownChoice<String> ddc = new DropDownChoice<String>("name", new PropertyModel<String>(this, "nameSelection"), names);
ddc.setRequired(true);
final Button submitButton = new Button("Submit") {
public void onSubmit() { doSubmitStuff(true); }
};
final Button cancelButton = new Button("Cancel") {
public void onSubmit() { doSubmitStuff(false); }
};
form.add(ddc);
form.add(submitButton);
form.add(cancelButton);
form.add(new FeedbackPanel("validationMessages"));
The problem is, I just added a validator, and it fires even if I press the cancel button, since the cancel button is attached to the same form as everything else. This could be avoided if the cancel button were in a separate form. As far as I know, I can't create a separate form because — due to the structure of the HTML — the separate form would be under the existing form in the component hierarchy.
Can I make the forms separate somehow in spite of the hierarchy? Or is there some other solution I can use?
EDIT:
In response to Don Roby's comment, this is a bit closer to what my code looked like back when I was trying setDefaultFormProcessing():
Form<Object> theForm = new Form<Object>("theForm") {
public void onSubmit()
{
PageParameters params = new PageParameters();
params.put("DocumentID", docID);
setResponsePage(Foo.class, params);
}
};
final CheckBox checkbox = new CheckBox("checkbox", new PropertyModel<Boolean>(this, "something"));
checkbox.add(new PermissionsValidator());
theForm.add(checkbox);
final Button saveButton = new Button("Save") {
public void onSubmit()
{ someMethod(true); }
};
final Button cancelButton = new Button("Cancel") {
public void onSubmit()
{ someMethod(false); }
};
cancelButton.setDefaultFormProcessing(false);
theForm.add(saveButton);
theForm.add(cancelButton);
theForm.add(new FeedbackPanel("validationMessages"));
There is an even simpler solution: call the setDefaultFormProcessing method on the cancel button with false as a parameter:
cancelButton.setDefaultFormProcessing(false);
This way, clicking the cancel button will bypass the form validation (and model updating), directly calling the onSubmit function.
It is possible to "nest" forms in wicket.
See this wiki entry
for some notes on how it works and this wiki entry for how it interacts with validation.
But for what you're after, the answer from Jawher should have worked and is much simpler.
Look at this example code for hints on getting that working.
I'm wondering if you've simplified your code too far in this posting. Can you produce a sample small enough to post that definitely has the problem?

Categories

Resources