how to retain dynamic dropdown values after page refresh using spring and jsp - spring

I am having 3 dropdowns.customername and companyname and servername.like this..
Based on Customer drop down i am populating Company Names.and based on Company names dropdown i am population server names using Spring and javascript.
If i click go button my page is refreshing.That time my droddown values are not retaining..
Can you any one suggest me regarding to this.
This is my code:
on click of customer dropdown i am calling onchange method in jsp.
<td valign="bottom">
<form:select path="CustomerId" id="customerDetails">
<option selected="selected" disabled="disabled">Select Customer</option>
<form:options items="${map.customerList}"
itemLabel="customerName" itemValue="customerId" />
</form:select> <br>
</td>
with this i am getting my customer dropdown values.Onchange of the customer i am getting company names..
<script>
$(document).ready(function() {
$("#customerDetails").change(function() {
var value1 = $('#customerDetails :selected').text();
$.ajax({
type : 'POST',
url : 'companynames',
data : {
selectedcustomername : value1
},
success : function(result) {
getcompNames(result);
}
});
});
});
</script>
Controller's code:
#RequestMapping(value = "/companynames", method = RequestMethod.POST)
public #ResponseBody String getEnvironmentNames(HttpServletRequest request,
HttpServletResponse response, #RequestParam String selectedcustomername) throws SQLException {
request.setAttribute("selectedcustomername", selectedcustomername);
System.out.println("selectedcustomername"+selectedcustomername);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("environments", new Environments());
List<Environments> environmentnamesList= loginDelegate.getEnvironments(selectedcustomername);
Collections.sort(environmentnamesList, new CustomComparator());
Gson gson = new Gson();
System.out.println("gson"+gson);
String jsonString = gson.toJson(environmentnamesList);
System.out.println("jsonString"+jsonString);
return jsonString;
}
Processing response of controller:
<script language="JavaScript">
function getcompNames(result){
$('#environmentName').empty().append('<option selected="selected" disabled="disabled">Select An Environment</option>');
var data = JSON.parse(result);
$.each(data, function(key, value)
{
$("#environmentName").append("<option>" + value.environments_name +" - "+ value.environments_purpose + "</option>");
});
}
This is my company ui code.
<td width="20%" nowrap="nowrap" class="boldFontSize3">
<b>Company:</b>
<select class="body" name="environmentName" id="environmentName" class="body">
<option selected="selected">Select a comapany name</option>
</select>
</td>
Like this way only i am getting servername.
Go button code:
<input name="Submit" value="Go" type="submit" class="boldFontSize3" />
after clicking go button my dropdown values are null
..my problem is when user click on go button my page is refreshing.i am getting customer dropdown values from modelandview object.For that i am getting customer dropdown values.But after page refresh i am not getting companynames and server.Because restcall will happen only onchange of customer Dropdown only.

Related

Springboot+Freemarker: cannot properly send "select - option" value to controller from freemarker page

I have a freemarker page with form wich contains several single select options, which are taken from DB.
Here I send the list of options to the page:
#GetMapping("/download")
public String getDownloadMethod(ModelMap modelMap, RedirectAttributes redirectAttributes){
modelMap.addAttribute("filesList", dao.listAllFiles());
modelMap.addAttribute("getFile", new Model());
return "download-form";
}
Then there is the form:
<form method="POST" action="/download-post">
<#if filesList??>
<#if filesList?size != 0>
<select name="files" value="getFile">
<#list filesList as file>
<option value="${file.id}">${file.id} - ${file.name}</option>
<br/>
</#list>
</select>
</#if></#if>
<br/>
<br/>
<br/>
<input type="submit" value="Get File"/>
</form>
We select one of the options and the id of the selected option should be sent to the post method in controller:
#PostMapping("/download-post")
public String postDownload(#ModelAttribute("getFile") Model model, RedirectAttributes redirectAttributes){
redirectAttributes.addFlashAttribute("message",
"You successfully downloaded '" + model.getId() + " " + model.getName()+ "'");
return "redirect:/downloadStatus";
}
Yet when I execute the code, I'm always getting "0" value of model.id and null of model.name
How should I properly bind the values in form so they would be sent to controller properly?
The difference from this question is that my list of option is not static but is selected from DB and there could be hundreds of options, which you cannot pre-define.

Can not call Spring controller when use ajax

I have a problem when use ajax with Spring
I want filter list result when I select region from select box or enter store name on screen so my idea is use Ajax to resolve this. But Ajax can not call to specific controller what is in url attribute of $.ajax
Below is my files:
JSP :
CSS id for is appliedStoreSearch
<form:form modelAttribute="appliedStoreInput" id="appliedStoreSearch">
<form:select path="regionId" cssClass="form-control">
<form:option value="" label="Toàn quốc"></form:option>
<form:options items="${listRegions}" />
</form:select>
<input type="email" class="form-control"placeholder="Tìm kiếm cửa hàng" name="storeNameInp" />
<div class="input-icon">
<i class="fa fa-search"></i>
</div>
</form:form>
Ajax
$(document).on('change','#appliedStoreSearch',function(e){
var input = $("#appliedStoreSearch").serialize();
e.preventDefault();
$.ajax({
url:"/promotions_controller/search_applied_store_ajax",
method:"POST",
contentType : "application/json;",
dataType:"json",
data:input,
success: function(data){
}
});
e.preventDefault();
});
Controller :
#RequestMapping(value="/search_applied_store_ajax",method=RequestMethod.POST,produces="application/json" )
public #ResponseBody List<AppliedStoreDto> searchAppliedStoreAjax( #ModelAttribute("appliedStoreInput")AppliedStoreInputDto appliedStoreinput){
System.out.println("in ra 1 so thu gi go");
List<AppliedStoreDto> listAppliedStore = null;
appliedStoreinput.setCompanyId(7);
try {
// get list applied store
listAppliedStore = promotionLogic.findAllAppliedStore(appliedStoreinput);
} catch (Exception e) {
logger.error(e.getMessage());
}
return listAppliedStore;
}
I have debugged Javascript then I retrieved data from form but Spring controller (/promotions_controller/search_applied_store_ajax) still can not be called by Ajax. There is not any things what is showed in console
Please help me, tks all!!!!
Given your ajax call has contentType of "application/json;" I would look at adding consumes = "application/json" to your RequestMapping and swapping ModelAttribute for RequestBody
Sean's answer is basically correct. Just adding the exact details. Function declaration should look like something like following
#RequestMapping(value="/search_applied_store_ajax",method=RequestMethod.POST,produces = { MediaType.APPLICATION_JSON_VALUE}, consumes = {
MediaType.APPLICATION_JSON_VALUE} )
public #ResponseBody List searchAppliedStoreAjax( #RequestBody AppliedStoreInputDto appliedStoreinput){

nested partial View calling HttpPost method 2 times

I have seen this question being asked few times here , but solution I saw are not generic , they are related to their specific code ..
I need to rectify the Work done by previous developer , the flow of ajax calls are wrong in code
In my Situation I have views like :
1.Index (Main View)
2.ParentCategoryList (partial View inside Index)
3. AddChild (partial View inside ParentCategoryList )
4. childCategorytree (Seperate View )
Problem is that from 2nd nested View (AddChild ) , whhen i click on save button ,httpost method is calling twice
My Index View
<div>
<div class="content" id="divparent">
</div>
<div class="content" id="dvChild">
</div>
</div>
its script
#section scripts{
<script type="text/javascript">
$('document').ready(function () {
//------------
$.get('#Url.Action("ParentCategoryList", "List")', function (data) {
$("#divparent").html("");
$("#divparent").html(data);
});
})
function addnewchild(url) {
$.get(url, function (data) {
$("#dvChild").html("");
$("#dvChild").html(data);
});
}
</script>
}
First Partial View inside Index (ParentCategoryList.cshtml)
#foreach (Bmsa.UI.Models.ListsResultModel data in Model)
{
<tr> <td><a onclick="addnewchild('#Url.Action("AddChild",
"List", new { id = #data.listID })')" >
</a> </td></tr> } </tbody> </table>
2nd Nested Partial View inside ParentCategoryList
#using (Ajax.BeginForm("AddChild", "List", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dvChild"
}))
{
<div > <input type="submit" value="Save" /></p></div>}
and Controller methods
public ActionResult ParentCategoryList()
{
//Code
return PartialView("ParentCategoryList", categoryList); }
//GET Operation to Load this View
public ActionResult AddChild(int id)
{
ViewBag.ParentID = id;
ListsAddModel addchild = new ListsAddModel();
addchild.parentListId = id;
return PartialView("AddChild", addchild);
}
[HttpPost] (**this method is calling twice--this is the problem** )
public ActionResult AddChild(ListsAddModel model,int id)
{
//Code
return RedirectToAction ("ChildCategoryListTree", new { id = model.parentListId });
}
and childCategorytree Partial view (also blank one)
I am not able to prevent this method to called twice . I tried e.preventDefault() in $.ajax call , but it is not working ...
I have tried to minimise the code , I think the problem is in RedirectToAction , but I am not sure
Any Help would be appreciated

Spring MVC Ajax Search Form Thymeleaf

So I'm trying to create a search form in the navbar of my site, and I'm using ajax to submit the form. I have other working search forms in my web app so I know how to do that. And I have the ajax submitting properly. I just don't know how to get the data from the form and use it in the controller to get the result that I want.
The way I'm doing the search function is by creating a searchForm.java object that has a string variable called searchString and I populate that and then query it against the database in the controller using spring data methods in my repository class.
So here's what my jquery ajax form looks like, and in the console on the chrome developer tools it returns "setSearch" like I tell it to in the controller, and I know that's an issue, I just don't really know how to fix it.
<script th:inline="javascript">
/*<![CDATA[*/
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).ready(function(){
$("#searchButton").on("click", function(ev) {
$.ajax({
url : "/setSearch/search",
type : "post",
data : {
"newSearch" : $("#newSearch").val()
},
success : function(data) {
console.log(data);
},
error : function() {
console.log("There was an error");
}
});
});
});
/*]]>*/
</script>
Here's my thymeleaf html page
<form action = "setSearch" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="newSearch"></input>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
</div>
<button type="button" class="btn btn-default" id="searchButton">Search</button>
</form>
This is my searchForm.java object
public class SearchForm {
private String searchString;
public String getSearchString()
{
return searchString;
}
public void setSearchString(String searchString)
{
this.searchString = searchString;
}
}
Here's my controller, and I know this won't work, because I'm returning a string and not a json object(I think that's right). But I tried to change it and I get a lot of errors, and I'm not sure how I should go about this.
#RequestMapping(value="/setSearch/search", method=RequestMethod.POST)
public #ResponseBody String search (#RequestParam String newSearch, ModelMap model)
{
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(newSearch);
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
Here's a working example of a non ajax search function in my controller, so you guys can see what I'm trying to do.
#RequestMapping(value="/setSearch", method=RequestMethod.GET)
public String searchGet(ModelMap model) {
SearchForm searchForm = new SearchForm();
model.put("searchForm", searchForm);
return "setSearch";
}
#RequestMapping(value="/setSearch", method=RequestMethod.POST)
public String searchPost(#ModelAttribute SearchForm searchForm, ModelMap model) {
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(searchForm.getSearchString());
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
Let me know if I left anything out or if you would need to see any more code to see my issue. Thanks in advance.
If you are only submitting one parameter and it will be restfull there is no need for form or POST
Here is a simple example of how I would do a search that returns a array of objects from database. I hope you can use it to implement what you need.
HTML
<form>
<label for="search_input">Search:</label>
<input type="text" id="search_input">
</form>
Javascript
<script>
$.get("/search", {term: $('#search_input').val()}, function(data) {
// do your data manipulation and transformation here
});
</script>
Controller
RequestMapping("/search")
public #ResponseBody List searchPost(#RequestParameter("term") String query) {
List<Object> retVal = getListOfObjectFromDbBasedOnQuery(query);
return retVal;
}
Lot simpler (from a logical perspective), remember in RESTfull terms post is used to create objects. Retrieving data use GET only.

passing drop downlist selected value to Ajax.ActionLink

i have a dropdown list in my view which is populated through model . i want to pass the selected value to
ajax link.
<select name="dd" id="dd">
#foreach (var item in Model)
{
<option value="#item.cid" >
#item.cname</option>
}
</select>
#Ajax.ActionLink("Submit", "Someaction" , new { id = } , new AjaxOptions { UpdateTargetId = "result" })
<div id="result"></div>
how should i route selected value of dropdown ? please help
Selected change action is the client side event, so you cannot handle this event with helpers. But you can use somethink like this:
<select name="dd" id="dd">
#foreach (var item in Model)
{
<option value="#item.cid" >#item.cname</option>
}
</select>
script
$("#dd").change(function() {
var selectedVal = $(this).val();
// in here you have ddl value
// you can pass this parameter with
// ajax and update your result div
$.ajax({
url : 'Home/SomeAction',
data : { selected : selectedValue },
...
success : function(result){
$("#result").html(result);
}
});
});
controller
public ActionResult SomeAction(int selected)
{
// selected is the selected value of DDL...
//return Json/PartialView
}

Resources