Handling post request with form data with multiple identical names in jsp - ajax

On the website a ajax post request is send to a jsp file, that reads the body and sends back a response that is used to refresh a part of the page. In the Ajax request I can see that the data with identical names is send. However, I can not read the data. With unique names I can retrieve the data in jsp. Changing the way the data is send is not an option, because there is too much code build around it.
This code reads the form data and prints it back on the website.
<h1>Facet <c:out value="${pageContext.request.getParameter('facet')}" /></h1>
<h1>Minprice <c:out value="${pageContext.request.getParameter('minPrice')}" /></h1>
"Minprice" is printed to the screen, but "Facet" isn't.

I found it! The request class has a different method for handling multiple identical parameter names, like which is often the case with the <select> and <option> tags. It is the "getParameterValues()" method. The following code gives me the result I was looking for.
<c:forEach items="${pageContext.request.getParameterValues('facet')}" var="item">
<h1>Facet ${item}</h1>
</c:forEach>

Related

What is the difference between "render a view" and send the response using the Response's method "sendResponse()"?

I've asked a question about what is "rendering a view". Got some answers:
Rendering a view means showing up a View eg html part to user or
browser.
and
So by rendering a view, the MVC framework has handled the data in the
controller and done the backend work in the model, and then sends that
data to the View to be output to the user.
and
render just means to emit. To print. To echo. To write to some source
(probably stdout).
but don't understand then the difference between rendering a view and using the Response class to send the output to the user using its sendResponse() method. If render a view means to echo the output to the user then why sendResponse() exists and vise versa? sendResponse() exactly sends headers and after headers outputs the body. They solve the same tasks but differently? What is the difference?
In ZF, rendering a view doesn't actually output any content. Instead the rendering process returns the content as a string to the caller. Zend_Application automatically takes care of taking the rendered view and inserting it into your layout (assuming you use layouts) through a placeholder, and putting that data into the Zend_Controller_Response_Http object which is ultimately responsible for delivering the content to the user. The reason for the Response object is so it can encapsulate your HTML output, and also manage any additional HTTP headers or redirects you want to send.
You can also manipulate further the contents of the response in the Response object prior ot sending the data to the client if you wish.
sendResponse() takes care of sending any headers (including the HTTP response code), checking for any exceptions that may have occurred (due to not being able to send headers or other reasons) and then sends the HTML which could include your layout and one or more rendered view scripts.
Hope that helps.
They are two very different things.
Rendering a view provides another layer in which you can template your data. This will allow you to easily dynamically populate HTML/templates keeping logic seperate from presentation.
Echoing data directly skips this step, and is usally reserved for reterning json/xml (data) responses to user instead of html response.
You didn't post which framework you are talking about but both should allow you to specify response headers.
Please don't oversimplify. Every server's purpose is to render resource but that doesn't mean they are all the same.

Client side to server side calls

I want to change the list of available values in a dropdown depending on the value selected in another dropdown and depending on values of certain fields in the model. I want to use JQuery to do this. The only hard part is checking the values in the model. I have been informed that I can do this using Ajax. Does anyone have any idea how I will approach doing this?
AJAX is indeed the technology your looking for. It is used to sent an asynchronous request from the client browser to the server.
jQuery has an ajax function that you can use to start such a request. In your controller you can have a regular method tagged with the [HttpPostAttribute] to respond to your AJAX request.
Most of the time you will return a JSON result from your Controller to your view. Think of JSON as something similar to XML but easier to work with from a browser. The browser will receive the JSON and can then parse the results to do something like showing a message or replacing some HTML in the browser.
Here you can find a nice example of how to use it all together.

Django Forms - Processing GET Requests

We have an existing Django form that accepts GET requests to allow users to bookmark their resulting query parameters. The form contains many fields, most of which are required. The form uses semi-standard boilerplate for handling the request, substituting GET for POST:
if request.method == 'GET':
form = myForm(request.GET)
if form.isValid()
# Gather fields together into query.
else
form = myForm()
The problem is that the first time the form is loaded, there's nothing in the GET request to populate the required fields with, so most of the form lights up with 'missing field' errors.
Setting initial values doesn't work; apparently, the non-existent values in the GET request override them.
How can we avoid this? I'm pretty certain we're simply not processing things correctly, but I can't find an example of a form that handles GET requests. We want errors to show up if the user hits the "Submit" button while fields are blank or otherwise invalid, but don't want these errors showing up when the form is initially displayed.
The positional argument to the forms.Form subclass informs Django that you intend to process a form rather than just display a blank/default form. Your if request.method == 'GET' isn't making the distinction that you want because regular old web requests by typing a URL in a web browser or clicking a link are also GET requests, so request.method is equal to GET either way.
You need some differentiating mechanism such that you can tell the difference between a form display and a form process.
Ideas:
If your processing is done via. AJAX, you could use if request.is_ajax() as your conditional.
Alternatively, you could include a GET token that signifies that the request is processing. Under this example, first you'd need something in your form:
<input type="hidden" name="action" value="process_form" />
And then you can look for that value in your view:
if 'action' in request.GET and request.GET['action'] == 'process_form':
form = myForm(request.GET)
if form.is_valid():
# form processing code
else:
form = myForm()
I'll also give you the standard, boilerplate point that it's generally preferable not to use GET for form processing if you can help it (precisely because you run into difficulties like this since you're using an anomalous pattern), but if you have a use case where you really need it, then you really need it. You know your needs better than I do. :-)
If your clean page load doesn't have any non form GET params, you can differentiate between a clean page load and a form submit in your view. Instead of the usual
form = YourForm()
if request.POST:
you can do
if request.GET.items():
form = YourForm(request.GET)
if form.is_valid():
...
else:
form = YourForm()
If your clean page load could have other params (eg email link tracking params) you'll need to use the QueryDict methods to test if any of your form params are in the request.
request.GET is and empty dictionary when you first load a clean form. Once you have submitted the form, request.GET will be populated with your fields data, even if the fields contain only empty data.
My first question is this, which I posted as comment:
Why not just use request.POST and the standard way of processing form data?
After considering everything here, perhaps what you are looking for is a way of processing data in your query string to populate a form. You can do that without using request.GET as your form.data.
In my own views, I take advantage of a utility function I created to add initial data to the form from request.GET, but I am not going to share that function here. Here's the signature, though. initial_dict is typically request.GET. model_forms is either a single ModelForm or a list of ModelForm.
def process_initial_data(model_forms, initial_dict):
Nevertheless, I am able to process the form through the standard practice of using request.POST when the form is POSTed. And I don't have to pass around all kinds of information in the URL query string or modify it with JavaScript as the user enters information.

how spring mvc tag works?

I am trying to write some kind of raw html to mimic what spring mvc tag produces after page rendering(and I do make them look exactly the same if you open them with a html element inspector). as I want to create dynamic input form using javascript. but it didn't work. it seems I had to use only what it offers: e.g. <form:input path="firstName" />.
to get the data binding working.
I thought the tag lib only help you to produce a html block that spring knows how to handle them in backend (action). from a web http perspective. what else it can send beyond a bunch of form data, and they should send the same thing. so I am really curious to learn what magic thing the tag lib dose beyond producing a html block.
the other thing I would like to know is where the model object is being hold when the form is being submit to a matched action. you know, you can get the model attribute by using #modelAttribute as the input parameter. is it in the original request object? or in the ActionRequest to which the dispatcherServlet build and put it. or even somewhere else?
thanks in advance.
I got it figured out. the raw html just works as spring tag does. as long as you are in the form tag block. you are okay to use raw html such as
<input type="text" id="abc" name="abc"/> just make sure name reflect your bean attribute path.
id is not mandatory and is just helping you to identify the very element. I guess I missed something when I work with the raw html by the time I ask the question. hope this helps for guys working with raw html approach, especially in case of dynamic input creation.

Codeigniter: Pass form variable into URI

Not sure if this can be done but it seems my main issue is because i have a default route to a method called "index." I want to be able to list all users tagged with a specific keyword. In addition, users can search for other users based on these keywords.
i.e.
www.domain.com/tags/apples
www.domain.com/tags/oranges
www.domain.com/tags/blueberry
It works fine if I go to the URL manually. I'm having issues getting it to work with a form field.
Snippet of the form_open:
<?=form_open('tags/');?>
<p>Search for Tag: <input type="text" name="tag" /></p>
<p><input type="submit" value="Search" /></p>
Here's a snippet of my controller:
function index() {
$data['result'] = $this->tags_model->searchByTag($this->uri->segment(2));
$this->load->view('tags_view', $data);
}
Here's a snippet of my router:
$route['tags'] = "tags/index";
$route['tags/(:any)'] = "tags/index/$1";
Now, I can easily fix all this if I have a method called search, but I don't want the URL to show up as www.domain.com/tags/search/orange.
When you create your form you set it to use POST variables instead of GET, that way they don't go through the url, that's codeigniter's default method for forms.
So your form_open code will generate the following code:
<form method="post" action="tags/" />
If you want them to got through url though, call the form opener this way instead:
form_open('tags/', array('method' => 'get'));
The same applies to any other attributes you want to specify for the form, just follow the same pattern attribute_name => attribute_value inside the array.
More info on the user guide
The problem here is that your form will be submitting all it's data to "/tags", with nothing trailing it, as POST data doesn't come in as part of the URL. Even if it was a GET request however, I don't think that CodeIgniter will take anything out of the querystring and use it as part of the routing segments.
I think what you should do is have a small Javascript function that automatically updates the form action parameter to be tags/<select option value> whenever the select value is changed. This way it will submit to the right place. In order to handle non-javascript enabled browsers, you could have a default action called tags/search that would simply analyze your form data and put out a 301 redirect to the proper tags/<location> once you'd figured it out.
It seems like a bit of overkill here however, as you could really point the form at tags/index and not worry about it. I'm not sure search engines index form submission locations, and even if they did, they certainly wouldn't index a form that submits to dynamic URIs in the way that you want it to. You could still link to the search result pages using tags/apples, etc, but the form could work quite normally just by going to tags/index.
I ended up redirecting the URL and passed the keyword into the URI.
i.e. domain.com/tags/view/

Resources