I have a JSP in which there is a select list containing entity kind names. When I select an entity kind I need to populate another select list with the field names of the selected entity kind. For that I call a JavaScript function on the onchange event.
In the JavaScript method I need to call a method in the backend that returns an arraylist that contains the field names of the selected entity kind.
How do I call the method with and without Ajax? Also how do I populate the second select list dynamically with the arrayList?
I'll describe two ways to go: with/without AJAX.
If you want to do a synchronous form submit you'll need to attach onchange event to your first select element:
<select name="select-one" id="select-one" onchange="this.form.submit()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
When done this way, the form will be submitted and first select option will be available as request.getParameter("select-one"), based on which you'll provide data for second dropdown population, typically forwarding to a JSP.
If you want to retrieve a list via AJAX and repopulate another dropdown, you can send an AJAX request and handle returned data in a callback function:
var val = $('#select-one option:selected').val();
$.ajax({
url: "servletURL",//servlet URL that gets first option as parameter and returns JSON of to-be-populated options
type: "POST",//request type, can be GET
cache: false,//do not cache returned data
data: {one : val},//data to be sent to the server
dataType: "json"//type of data returned
}).done(function(data) {
var second = $("#select-two");
$.each(data, function() {
options.append($("<option />").val(this.value).text(this.label));
});
});
When done this way, the second dropdown will be repopulated without page refresh.
Write a JavaScript function names callAJAX on the onchage event of your select drop down
In your callAJAX function , make an ajax call to the back end, get the response from the server, and populate the new drop down with the response coming in your ajax call
I hope you can make ajax calls , if not let me know.
You want to load your list dynamically from backend. You must communicate with your server either:
with a page load (form submit)
or without a page load(ajax).
If AJAX is not your requirement, I suggest you do it by form submit(with page load) first because it's simple and easier for beginner.
Agree with Jai. You will have to submit that form to the java method, then your java method will return the arrayList. Of course if you form submit, your page will be refreshed and I'm not sure if your previously selected values will still be selected on the form. I'm not too clued up with this method of doing it. I prefer to use jquery.
With jquery you can do it like this:
$.ajax({
url: "/MyApp/MyClass/getArrayList",
type: "GET",
data: "selectedEntity=" + s_entity,
success: function(response){
//handle returned arrayList
},
error: function(e){
//handle error
}
});
Put this in a function. Pass your selected entity as a parameter and handle the response in the success part. Of course your java method should map 'selectedEntity' to a parameter in the method header. In Spring it's done like this:
private #ResponseBody ArrayList getArrayList(#RequestParam("selectedEntity") String entity)
Related
I have a URL say abc.com/somecontroller?someparam=1 which renders a form. Form on submit sends the form params to /ajaxAction
Is there a way I could get this abc.com/somecontroller?someparam=1 (i.e. the form URL?)
I am more interested in getting the someparam value from the URL of the form.
PS: the above URL abc.com/somecontroller?someparam=1 is dynamically generated, so I can not access it otherwise.
And request.forwardURI will give me /ajaxAction (i.e. the URL of the action in form and not the url of the form itself).
EDIT:
I have no control over form as it is also dynamic and user has hundreds of templates to select from. Each template has different no. of fields.
So if I would prefer some other way to get the URL.
Why don't you use javascript in form and add to ajax request array with GET params? (or with the url of the action which generated form)
You can get them from original request f.e. by this script.
While rendering the GSP of your form, you can do like this:
myaction.gsp
<html>
<body>
<!-- Your content -->
<script>
var paramsString = '${params.collect { k, v-> "$k=$v" }.join("&") }';
</script>
</body>
</html>
So, when you GSP is rendered, the script tag will have something like this (for a URL abc.com/somecontroller?someparam=1&foo=2:
var paramsString = 'someparam=1&foo=2';
Now, in your AJAX code, you can pass that string as the query arguments:
$.ajax({
url: '/ajaxAction?' + paramsString
/* rest of the AJAX code */
});
Now, in your ajax controller action, you can simply do the params.someparam.
EDIT
Well, I just realized that you don't have to any GSP stuff I mentioned above. Simply do the AJAX call like this:
$.ajax({
url: '/ajaxAction' + location.search
/* rest of the AJAX code */
});
The location.search will give you the direct string: ?someparam=1&foo=2
I ended up using flash to store the someparam
In my controller which is being used to render the form at abc.com/somecontroller?someparam=1 I use flash as this:
flash.put("someparam", params.someparam)
This worked as a quick workaround to the issue. I feel this would work well in situations where I have no control over the gsp.
If anyone finds any issue, please comment otherwise I will mark this as the answer.
I have some code:
$(document).ready(function(){
$(":button").click(function(){
var formData = {"field1":field1, "oper1":oper1, "value1":value1, "field2":field2, "oper2":oper2, "value2":value2, "field3":field3, "oper3":oper3, "value3":value3};
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", formData, function(response){alertHere(response)});
})
})
function alertHere(response){
alert("Post successful");
alert(response);
renderResults();
}
that posts form data and queries for the data and sets the session attribute with
session.setAttribute("directoryString", xml);
when a button is clicked. In the response function, renderResults is called, which grabs the returned xml:
function renderResults(){
alert("inside renderResults()");
element = document.getElementById("person");
xmlString = '<%=session.getAttribute("directoryString")%>';
console.log('XML String: ' + xmlString);
The rest of the function is written to parse out the xml and display it on the page.
My problem is that when I first go to the page and post data, the xmlString variable is null. When I refresh the page and go back to "Page Source" in my web console, the variable is set correctly. I'm not exactly sure what's going on. Is it possible that my function is trying to call the session attribute before it's set?
P.S. I know that scriplets aren't the best way of doing it, but that's the way we do it around here.
<%=session.getAttribute("directoryString")%> will only be evaluated when the JSP is rendered into the HTML page. Once the rendered HTML is in the browser, it can only be changed either by:
reloading the page
JavaScript.
Make an ajax call to get the updated value of the attribute and update the variable (for example, you can set document.myXmlString = '' and use that value in your renderResults.
I have a very complex scenario where i need to change the java objects(basically HashMap ) from jquery get Request and get the response and print that in the jsp. User can send number of request and get seperate response from servlet based on request and display the data.
after every request i have to put the map in session and than in another request i get the same in session and do the updates and put it back in session.
JqueryGet(parameter) to Java.
Updating Hashmap according to parameter.
Putting hashmap in session . ( session.setAttribute("map",map))
sending response back to Jsp in jquery and print results in jsp.
Than another request send to Java .
it will get the map from session session.getAttribute("map",map) and than update the map based on new request .
Put the map again in session and so on....Than i have a submit button finally which will show the new data on the page and than update the server.
Is this the right approach ? My functionality is working fine as of now in Dev environment. But i am worried whether i should use DOM. if i will use DOM it will be very complex since i have to manipulate much values of Hashmap based on request.
Here is the jquery code :
$.ajax({
url: '<%=portalContext.createTemplateProcessURI()%>'
+'?s1='+ $("#networkBox1").val()+'&box1=Box1&tick=add&val1='+ allvs+'&s2='+ $("#networkBox2").val()+'&box2=Box2&val2='+ allvs,
type: 'get',
dataType: 'text',
async: false,
success: function(data) {
Processbox(data); // This function displaying the result.
}
});
dude, first of all, I think after you get your data from back end side, your java object has already changed to json object. I think your flow has no problem, because once you change to DOM, then all the data is send through front side but not back end side, if you use session, actually you handle your data at back end side, for me, I prefer the second one.
Here is my idea:
1.set a dom object in your page with the data get from your ajax
$(domId).val(value get from ajax);
2.If your don't want to show the data, use hidden type input in your jsp form
<input type="hidden" id="domId" name="domName">
3.once you click submit button, handle your data in your servlet
String data = request.getParameter("domName");
session.setAttributes("sessionData", data);
Hope this will help you.
Im new to ajax. I want to redirect to servlet with the parameter value of the select box to my servlet. This is my code and its not retrieving values when I use request.getParameter("type") it gives me a null.
<script>
$(document).ready(function() {
$('#type').change(function() {
$.get('pickasset', function(responseJson) {
var type = $('#type').val();
$.ajax({
type:'POST',
url: 'PickAssetServlet',
data: type
});
});
});
});
</script>
<form action="pickasset" method="post">
<select id="type" name="type">
<option value="Non-Sap">Non Sap</option>
<option value="Sap">Sap</option>
</select>
</form>
When i change the select box, it must go to servlet and do logic there.
send your data like this-
data: { type : type }
If you're not getting the selected option from the select field, you need to use
$('#type').find(":selected").text() to retrieve the selected option. val() doesn't work with select fields. Also do what pXL said because that's how you send data with jQuery ajax methods
Check box value must be obtained from checkbox in the right way, as mentioned in jQuery docs (http://api.jquery.com/val/), just pay attention to multiple select, you're gonna have an array of values. You are doing it right, according to docs.
var varValue = var type = $('#type').val();
Then sending data as 'json' you will be able to read them with request.getParameter('type')
data: { "type" : varValue }
If you still get null, try to check if your "type" param and his value are in the request (chrome request inspector will be usefull, then check it in the debugger).
.
P.S.
Just check if you have something in your webapp filterchain that may wrap you request or hide some params, in some large web-app you get lost very easly.
I am a building project in which I am using java-beans,jsp and servlets. I need to send the response to the client on the same page from where request was made with a slightly modified html. But when I(server) sent the request to the jsp page, the controls in the form are getting reset to their original value. But I don't want to override the user's input after the request was made. One way to achieve this is to take value of the property for each control in the form when request is made and then set them again while responding. Actually there are a large number of controls in my form, taking values of each doesn't seem efficient.
So is there some other way to keep the form in the jsp file unchanged while responding to the client.
you can use ajax for what you are asking, or you have to save the data on form submit, in session or some place and set them back again while responding. Apart from that I think there is no other way you can retain form data even after page reload.
Thanks
Chakri
Why dont you use iframe ? so you dont have to refresh the whole page when the request is made to the same page.
Instead of making the action of the form to the same page, call a javascript function that set the parameters in the link and then
var f = document.getElementById('iframe');
f.src = 'newlink';
f.contentWindow.location.reload(true);
This populated the iframe with the latest content
function openOffenderInfo(i)
{
$.ajax({
url:'../loginServlet',
type: 'POST',
success: function(data)
{
alert("reset your div values in this block");
.... for example .....
documnet.getElementById('reloading Div').innerHTML=data;
},
error: function(data)
{
alert("error");
}
});
}
URL : c=name of the servlet you want to call
this servlet calculates the data and gives the new data you want to reset in your div
success : this is the function which will be executes if your ajax call is made successfully
so you can set the values of your reloading part inside this function
I hope this might serve you the purpose