We pull data from server and for that If we are using Struts, then we can pull either by submitting a page which MVC Architecture or we cam make an AJAX call but conventions is of using forms and render response but we also face challenges to give rich user experience, so we compromise convention and start using excessive AJAX, so how we should make balance between two?
I personally think that AJAX should be used for displays updates and form submissions should be done via a page reload. Reasoning?
When submitting forms, you are telling the application to do something. Users tend to want to feel that it was done. When a page doesn't reload, users are often left wondering "Did that work?". Then they have to check to make sure what they did was right.
On the other hand, when you are displaying a chart or something, and the user says to "display 2011 data....now 2012 data" for instance, they aren't "doing" something (creating new entities, sending emails, etc). So AJAX can provide a nice user interface in this case. Page reloads would be annoying here.
In conclusion, I think form submission should be done via page reloads (let the user see it working), whereas display updates should use AJAX (prevent annoying page reloads).
Of course, this is a preference thing. Some of my company's applications use AJAX all over. But those are the applications that are the most difficult to maintain and debug. ;)
Regular old HTML form submission and fancy ajax forms are not mutually exclusive.
First, make the plain HTML form work correctly. Then, add javascript to hijack the form and send an ajax request.
The controller and model don't care if the user's browser supports (or has enabled) javascript. The rendered view is decided by whether the call was made with javascript or a simple form submission. This is one of the strengths of the MVC pattern, not a constraint.
I think that the choice between the two is somewhat intrinsic:
a form submission is synchronous and it reloads the page.
an ajax call is asynchronous and it does not reload the page.
If a certain action will change a lot of UI elements or needs to poll a lot of data to be rendered, I would go with form submission. On the other hand, if a certain action is used for simple actions, like populating a select box or improving user experience, then I would go for an AJAX call.
There is nothing avoiding you to use as many ajax calls or form submissions as you need, so in the end is up to you.
In this day and age, there is virtually no case to use the old standard HTML form submission method (other than pure nostalgia, or perhaps not knowing).
The <form> tags themselves can still be useful if you want to take advantage of the .serialize() function (which grabs all name-data pairs within the form into a query string), but other than that we don't need to use <form> tags at all these days.
Using AJAX, the developer has more control over the entire process, in a more condensed code base. But more importantly, we just don't do things that way anymore.
Consider:
(Old Style - Forms) When an HTML form submits: (a) it gathers the form field name= attribute values (these become the defacto variable names) (b) together with user-entered data in the form fields (which become the variable values), and posts these data-pairs to a PHP file (as specified in the action= attribute on the form tag). THEN, the page changes to that other page, causing a noticeable refresh of the screen and loss of all previously inputted user data. Even using the trick action="", wherein the form data is posted back to the same page it started from, the page is still reset/refreshed.
(New Style) Exactly the same process can easily be programmed using javascript/jQuery - except that the page does not refresh. All previously entered user data/text can remain undisturbed.
Back to your question:
With the old-style HTML form submission, the page changes - so if you want to do field validation you use javascript/jQuery to cut into the submit process, thus:
$('myform#btnSubmit').click(function(){
var some_fields_failed = false;
//check form field values here, set: some_fields_failed = true
if (some_fields_failed){
return false; //halts the HTML Form Submit process and returns control to the user
}
});
in which case you already are using most of the AJAX construct that would replace the HTML form submission process.
This simple introduction to AJAX provides some compelling reasons to use AJAX instead of the old-style HTML Form Submission process:
AJAX is a developer's dream, because you can:
Update a web page without reloading the page
Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded
Send data to a server - in the background
Note that you can write ajax code in pure javascript, but until very recently it was considerably simpler (much less typing, more consistent) to use the jQuery (javascript) library. Hence, all examples above use jQuery. To include jQuery in your project, it is only necessary to include a reference to the jQuery library:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
StackOverflow maven, Schabse Laks, created a simple jQuery tutorial that is worth stepping through (IMPORTANT: Use Down Arrow to step through the pages)
If you have errors between submissions of data the only forms method you could check on the server. On the other hand if you make Ajax calls you could check that errors on the client side. So, out of this different technologies of transmitting data we could follow a decision that they serve different purposes.
When sending a form with AJAX, you generate the POST request and not the browser, so you have more control over it. Even if you don't need that control to begin with, in time it might become necessary.
One case would be protection against CSRF attacks on forms. It can be implemented by adding a hidden form input field containing a CSRF token, which is sent together with the form data. But a preferred implementation would be to add a custom header to the submitted POST request. However, you can't do the latter when using the old form submission method - the browser composes the request and you can't add your own headers.
Related
I am currently learning JSF and was rather amazed and puzzled when I realized that whenever we use <h:form>, the standard behavior of JSF is to always show me the URL of the previous page in the browser, as opposed to the URL of the current page.
I understand that this has to do with the way JSF always posts a form to the same page and then just renders whatever page the controller gives it back to the browser which doesn't know the page location has changed.
It seems like JSF has been around for long enough that there must be a clean, solid way to deal with this. If so, would you mind sharing?
I have found various workarounds, but sadly nothing that seems like a real solid solution.
Simply accept that the URL is misleading.
Append "?faces-redirect=true" to the return value of every bean's action and then
figure out how to replace #RequestScoped with something else (Flash Scopes, CDI conversation, #SessionScoped, ...).
accept to have two HTTP round trips for every user action.
Use some method (e.g. 3rd party library or custom code) to hide the page name in the URL, always using the same generic URL for every page.
If "?faces-redirect=true" is as good as it gets, is there a way do configure an entire application to treat all requests this way?
Indeed, JSF as being a form based application targeted MVC framework submits the POST form to the very same URL as where the page with the <h:form> is been requested form. You can confirm it by looking at the <form action> URL of the generated HTML output. This is in web development terms characterized as postback. A navigation on a postback does by default not cause a new request to the new URL, but instead loads the target page as content of the response. This is indeed confusing when you merely want page-to-page navigation.
Generally, the right approach as to navigation/redirection depends on the business requirements and the idempotence (read: "bookmarkability") of the request (note: for concrete code examples, see the "See also" links below).
If the request is idempotent, just use a GET form/link instead of POST form (i.e. use <a>, <form>, <h:link> or <h:button> instead of <h:form> and <h:commandXxx>).
For example, page-to-page navigation, Google-like search form, etc.
If the request is non-idempotent, just show results conditionally in the same view (i.e. return null or void from action method and make use of e.g. <h:message(s)> and/or rendered).
For example, in-page data entry/edit, multi-step wizard, modal dialog, confirmation form, etc.
If the request is non-idempotent, but the target page is idempotent, just send a redirect after POST (i.e. return outcome with ?faces-redirect=true from action method, or manually invoke ExternalContext#redirect(), or put <redirect/> in legacy XML navigation case).
For example, showing list of all data after successful editing, redirect after login, etc.
Note that pure page-to-page navigation is usually idempotent and this is where many JSF starters fail by abusing command links/buttons for that and then complain afterwards that URLs don't change. Also note that navigation cases are very rarely used in real world applications which are developed with respect to SEO/UX and this is where many JSF tutorials fail by letting the readers believe otherwise.
Also note that using POST is absolutely not "more secure" than GET because the request parameters aren't immediately visible in URL. They are still visible in HTTP request body and still manipulatable. So there's absolutely no reason to prefer POST for idempotent requests for the sake of "security". The real security is in using HTTPS instead of HTTP and checking in business service methods if currently logged-in user is allowed to query entity X, or to manipulate entity X, etc. A decent security framework offers annotations for this.
See also:
What is the difference between redirect and navigation/forward and when to use what?
JSF implicit vs. explicit navigation
What URL to use to link / navigate to other JSF pages
Bookmarkability via View Parameters feature
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
When should I use h:outputLink instead of h:commandLink?
Creating master-detail pages for entities, how to link them and which bean scope to choose
Retaining GET request query string parameters on JSF form submit
Pass an object between #ViewScoped beans without using GET params
I'm building a page that has a search box that will populate a grid on the same page. There is also a button the user can select to bring up a "window" (JQuery UI "pop-up" in the same page) that lets the user configure said grid.
These are two separate forms but I don't want what was submitted as part of one to undo the other (so when the user submits to change the grid layout the search needs to re-run as well.
I'd rather not store things in session for this since that brings with it its own issues (search results may be large, shouldn't be saved when the page is re-entered later, etc.).
I've considered doing "one large form" (i.e. surrounding all the inputs) for the entire page that is backed by a form backing bean. I would then use which button is clicked to determine the action to take. There will eventually be other buttons on the page as well to add more functionality. This would be similar to how .NET (non-MVC) handles things.
I'm interested in how others may have solved similar challenges. Are there potential issues with my approach that I'm not seeing? Better ways that work with the framework?
What do you mean with:
but I don't want what was submitted as part of one to undo the other
. Are you referring to posting the form and loading the whole page, which in turn will "reset" the other form?
If that is the case I would still keep one page with two forms and make the posts using Ajax (as you may know jQuery makes this a breeze). Upon receiving a response for either call you will need to update the other form accordingly.
Note that you may still have your forms in two separate views if it helps keeping the code clean and then pull their html with Ajax calls into another view. But my point is that at the end I would still keep both in one page since it sounds like they depend on each other so updating one when the other changes may be easier this way,
Let me know if I misunderstood your question.
This is my first time with wicket, so please bear with me.
Most examples in wicket show how with a wicket id you can automagically replace the inner HTML with different things. Using this knowledge I've hand written a form in HTML with lots of formatting and JQuery for different things, and only using Wicket to autogenerate the info for 2 select boxes. However when I try to parse the submitted information on the Wicket side, I get confused.
The only way I've figured out that's easy is using RequestCycle.get().getRequest().getRequestParameters(). to get all the passed info. It works, but I don't think that's the ideal way to use Wicket. There also seems to be a way with request handlers but I have no idea where to start, especially since a lot of documentation is out of date with the new 6.0.0 release.
What is the way I'm supposed to use Wicket with forms? Do I hand write most of the form, only let Wicket autogenerate some of the info, and use RequestCycle? Do I write a skeleton form, have Wicket autogenerate the rest, and use lots of submit handlers? Where is this documented in an easy to understand beginner tutorial?
Note: My form has several fields that are created dynamically (think "click here to add more options") and is submitted in the background with AJAX, verified, then cleared. This might complicate the Wicket side of things, but is a functional requirement
With Wicket you can think of HTML markup as if it was a template. Markup is actually almost-standard HTML. You can (and should) define wicket:id attributes for everything that will have certain behavior or logic attached (forms, buttons, links), or require some server-side processing (such as form components or nested custom components or panels). Everything else will be output in the response as it is in the markup.
Wicket will handle form submission and process the request for you. In Wicket, form components are usually defined server-side, and added to a Form component. In the Form component's onSubmit(), Wicket will have already processed the request, and the submitted values will be available in the FormComponent's Models.
So, the ideal way for Wicket to handle form submission would involve the server-side creation of any components in the form.
The following Wicket Examples page shows a basic Form with some FormComponents in it: Wicket Examples - forminput. You can even see its source code.
Also, you might find the following Wicket wiki page useful: How to do things in Wicket - Forms.
Regarding dynamic component creation, whenever a new dynamic component has to be created, you could for instance make an Ajax request that creates the component server side (wrapped in a ListView, for example), and get markup refreshed in the ajax callback.
There's an example of such a list here: Wicket in action - Building a ListEditor form component
Just to add, I found the Wicket in Action book to be an excellent resource for learning Wicket. Chapter 6 - Processing user input using forms elaborates on the subject.
I need to create a very simple application:
I need to have a form that submits data to a servlet
The servlet then queries a database to retrieve a list of reports based on the criteria given by the form
The returned list of documents has to displayed in a div on a .jsp page
I am not sure about the last one (number 3). I know how to call the doPost or some other method using jQuery (but not when triggered by a button), only using a timer, but I am sure it's a similar thing. But I want to keep it as simple as possible and avoid jQuery if possible.
If I call the servlet and return the data without using jQuery, how can I specify the location (i.e. which div) I want it to be returned in.
Where you display the contents of your Ajax request is up to the client-side Javascript.
The servlet will just create the data (either as HTML, or as JSON or XML, depending on what you need on the client).
If you do not want to use jQuery (or prototype.js, or something similar), you have to code the logic for firing off the Ajax request, and for parsing the result (including how to display it) yourself.
I'd say, stick with jQuery. That will keep it "as simple as possible".
If you are not sure how to start a new request when a button is clicked, check out this tutorial.
I am trying to clear everything on my HTML form when I visit it from a hyperlink entry.
Any ideas? My development language is java.
are you using session-scoped data? if so, close your browser and open it again.
I'm not sure the application is, but one way to accomplish this would be to use JavaScript. For example, if it is acceptable to clear the form every time that page is visited you could write a quick function that clears the form when the page is loaded (i.e., using the onload event).
If you only want to clear the form when the page is hit from that link you could add a param to the URL (e.g., clearForm=true) and use JavaScript to pick up the query string and clear the form when that parameter is present.
This is, of course, a purely client-side solution. For a server-side solution it would be helpful to know what framework you are using.