Populate dropdown based on another dropdown selection Spring MVC AJAX - javascript

I have 2 dropdowns: one for categories and one for subcategories. Based on what category I select on the first dropdown I want that the second dropdown to be dynamically populated with the subcategories of the selected category. This is what I have so far:
Controller to populate the first dropdown:
#RequestMapping(value = "/post_project", method = RequestMethod.GET)
public String postProjectPage(Model model) {
Project project = new Project();
List<Category> categoriesList = categoryService.getAllCategories();
model.addAttribute("projectForm", project);
model.addAttribute("categoriesList", categoriesList);
return "post_project";
}
JSP:
<form:form id="post_project" action="/post_project" method="post" modelAttribute="projectForm">
<form:select class="form-control" id="selectCategory" path="category">
<option value="">-Select-</option>
<form:options items="${categoriesList}" itemValue="id" itemLabel="category_name"/>
</form:select>
For the subcategories I have the following controller:
#RequestMapping(value = "/post_project", method = RequestMethod.POST)
public #ResponseBody List<Subcategory> getAllSubcategories(#RequestParam(value="categoryId") int categoryId) {
return categoryService.getAllSubcategories(categoryId);
}
JSP:
<form:select class="form-control" id="selectSubcat" path="subcategory">
<option value="-1" label="-Select-"/>
</form:select>
For populating the second dropdown I used AJAX, but I am very new with this and I don't know if it is right.
("#selectCategory").change(function(){
var categoryId = $(this).val();
$.ajax({
type: 'POST',
url: "/post_project",
data: {"categoryId" : categoryId},
success: function(data){
var slctSubcat=$('#selectSubcat'), option="";
slctSubcat.empty();
for(var i=0; i<data.length; i++){
option = option + "<option value='"+data[i].id + "'>"+data[i].subcateogory_name + "</option>";
}
slctSubcat.append(option);
},
error:function(){
alert("error");
}
});
});
Of course it does not work. When I select a cateogry nothing shows up in the second dropdown. I don't know what to do anymore and I've tried everything. Can someone please tell me what I am doing wrong?

Make you request as a GET:
("#selectCategory").change(function(){
var categoryId = $(this).val();
$.ajax({
type: 'GET',
url: "/categories/" + categoryId,
success: function(data){
var slctSubcat=$('#selectSubcat'), option="";
slctSubcat.empty();
for(var i=0; i<data.length; i++){
option = option + "<option value='"+data[i].id + "'>"+data[i].subcateogory_name + "</option>";
}
slctSubcat.append(option);
},
error:function(){
alert("error");
}
});
});
Server Side controller method:
#RequestParam is used to get the query parameters. So, it would be like ..../post_project?categoryId=1
Instead of #RequestParam use #PathVariable as below:
So to get the subcategories, you have #RequestMapping like .../categories/1
#RequestMapping(value = "/categories/{categoryId}", method = RequestMethod.GET)
public #ResponseBody List<Subcategory> getAllSubcategories(#PathVariable("categoryId") int categoryId) {
return categoryService.getAllSubcategories(categoryId);
}

Try to add the contentType & dataType to your Ajax Call :
` ....
$.ajax({
type: 'POST',
url: "/post_project",
data: {"categoryId" : categoryId},
contentType:"application/json; charset=utf-8"
dataType:"json",
........`
and change your controller to Post a Json Request :
#RequestMapping(value = "/post_project", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)

Related

How do I get asp-items to populate a select when adding select element to a div?

Using Javascript to add a select dropdown list when a button is clicked, but the select isn't being populated with the data from the viewmodel. Essentially this code creates what I want, but the asp-items are not populating the select aside from the default "Select Column Name" option.
How would I get this asp-items to populate from the viewmodel selectlist, "Model.SelColumnNames"?
<script>
$('.addSort').click(function() {
$('.block:last').before('<div class="block"><select asp-for="SelColumnNameAdditional" asp-items="Model.SelColumnNames" style="width: 30%;"><option value="">Select Column Name</option></select>   <select style="width: 15%;"><option value="1">Ascending</option><option value="2">Descending</option></select>   <span class="remove">Remove Option</span></div>');
});
</script>
Edit:
I can already populate it properly as a dropbox in the HTML section of my viewpage using this:
<select asp-for="SelColumnNameAdditional" asp-items="Model.SelColumnNames" style="width: 30%;">
<option value="">Select Column Name</option>
</select>
I would like the script code to be able to create a div with the same populated dropdown in javascript. When I do that, asp-items doesn't pull from the viewmodel like it does in the HTML code. Why is that?
If you are using Javascript, you need to get data using ajax. This is what I have so far.
Controller/ViewModel
public class JaesonViewModel
{
public string value { get; set; }
public string text { get; set; }
}
public class HomeController : Controller
{
public ActionResult GetViewModel()
{
var list = new List<JaesonViewModel>();
var j = new JaesonViewModel { text = "text1", value = "value1" };
list.Add(j);
var j2 = new JaesonViewModel { text = "text2", value = "value2" };
list.Add(j2);
return Json(new { Items = list.ToList() }, JsonRequestBehavior.AllowGet);
}
public ActionResult Index10() //I am calling index10 to start--the view is index10
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index10</title>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('.addSort').click(function () {
$.ajax({
type: "GET",
url: "/home/GetViewModel",
async: false,
cache: false,
dataType: "json",
contentType: "application/json",
success: function (jsn) {
jQuery.each(jsn.Items, function (index, itemData) {
$('.dropdown').append('<option value=' + itemData.value + '>' + itemData.text + '</option>');
});
},
error: function (jqXHR, exception) {
var status = jqXHR.status; //400
var message = jqXHR.responseText;
var ex = exception; // 'abort' for example
alert(status + " " + message + " " + ex);
}
});
});
});
</script>
</head>
<body>
<input type="button" class="addSort" value="Click Me" />
<select class="dropdown">
</select>
</body>
</html>

Controller not getting called though AJAX

I have a jsp page with 2 dropdown. the second dropdown should populate based on the value selected from first dropdown I am using AJAX for this to call a controller method on selecting the first dropdown to return the values for the second dropdown as json. On clicking submit entire form will be submitted to controller method. But on selecting the first dropdown, I am not getting any request on the controller method.
Jsp file
alert("Ok");
("#selectCategory").onChange(function() {
var categoryId = $(this).val();
alert(categoryId);
$.ajax({
type: 'GET',
url: "/categories/" + categoryId,
success: function(data) {
var slctSubcat = $('#selectSubcat'),
option = "";
slctSubcat.empty();
for (var i = 0; i < data.length; i++) {
option = option + "<option value='" + data[i].id + "'>" +
data[i].subcateogory_name + "</option>";
}
slctSubcat.append(option);
},
error: function() {
alert("error");
}
});
});
<form action="/show" method="post" modelAttribute="model">
<select class="form-control" id="selectCategory" name="sel">
<option value="Alto">Alto</option>
<option value="Esteem">Esteem</option>
</select> <br>
<select class="form-control" id="selectSubcat">
<option value="-1" label="-Select-" />
</select>
<input type="Submit" value="Submit" />
</form>
Controller method
#GetMapping("/categories/{categoryId}")
#ResponseBody
public List<String> get(#PathVariable("categoryId") String categoryId)
{
System.out.println("inside controller get "+categoryId);
ArrayList<String> l= new ArrayList<String>();
if(categoryId.equals("Alto"))
{
l.add("Alto Model 1");
l.add("Alto Model 2");
return l;
}
else if(categoryId.equals("Esteem"))
{
l.add("Esteem Model 1");
l.add("Esteem Model 2");
return l;
}
return null;
}
If I make a separate rest call to that controller method , I am getting the response as json [
"Esteem Model 1",
"Esteem Model 2"
], but through ajax, the request is not going.I am new to Ajax. Can someone please correct me if the below ajax code is wrong ?

No converter found for return value of type: class com.google.gson.JsonArray

I am developing an application where I have two drop down lists. When I select a value from first drop down, second drop down, an ajax call happens to controller and returned list should populate in second drop down list. I have tried below code.
jsp form:
<form:form modelAttribute="place" action="getWeather">
<table>
<tr>
<td><form:label path="country">Country:</form:label></td>
<td>
<form:select path="country" id = "countryList">
<form:option value="#">--Select--</form:option>
<form:options items="${CountriesList}"/>
</form:select>
</td>
</tr>
<tr>
<td><form:label path="city">City:</form:label></td>
<td>
<form:select path="city" id = "cityList">
</form:select>
</td>
</tr>
</table>
</form:form>
<script type="text/javascript">
document.getElementById("countryList").addEventListener("change", myFunction);
/* $(document).ready(function(){
alert("sample msg");
}); */
function myFunction(){
var id = $(this).val()
/* var Country = { "Country" : id }
alert(Country);
alert(JSON.stringify(Country)); */
$.ajax({
type: "GET",
url: 'GetCities/' + id,
dataType: 'json',
success: function(data){
var slctSubcat=$('#cityList'), option="";
slctSubcat.empty();
for(var i=0; i<data.length; i++){
option = option + "<option value='"+data[i] + "'>"+data[i] + "</option>";
}
slctSubcat.append(option);
}
});
}
</script>
Controller method:
#RequestMapping(value = "/GetCities/{country}", method = RequestMethod.GET)
public #ResponseBody JsonArray getCities(#PathVariable(value="country") String Country){
List<String> cities = getWeatherService.getCities(Country);
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(cities, new TypeToken<List<String>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
Ajax call is successful and getting data in list. But When pass the list to jsp in the form of JsonArray, it is giving exception like below.
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.google.gson.JsonArray
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:225)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:182)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:119)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I have tried passing List directly, but same issue. Please help me to find the solution.
Finally able to resolve this issue. Instead of returning JsonArray from controller, I have just returned Json string. It worked.
#RequestMapping(value = "/GetCities/{country}", method = RequestMethod.GET)
public #ResponseBody String getCities(#PathVariable(value="country") String Country){
List<String> cities = getWeatherService.getCities(Country);
Collections.sort(cities);
Gson gson = new Gson();
String json = gson.toJson(cities);
return json;
}

Trying to display 4 concate item in dropdownlist from database

I'm trying to bind and display 4 concatenate item in dropdownlist using ajax.
Like this eg. (127,CoilWt,1,KGS ) one of the value in dropdownlist should appear like this.from database.
In database i am selecting
`select CODE_VALUE,CODE_DESC,CODE_SUB_VALUE,CODE_SUB_DESC FROM TCODE
html part
<td><select class='form-control' id='Certific'><option value='' disabled='disabled' selected='selected'>Please select a name</option></select></td>
script part
$(function () {
$.ajax({
type: "POST",
url: "TDC.aspx/GetCertificate",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var Certific = $("[id*=Certific]");
Certific.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
Certific.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
c# side
public class GetCertificate
{
public int ID { get; set; }
public string Code_Desc { get; set; }
}
[WebMethod]
public static List<GetCertificate> GetCertificate()
{
string connStr = ConfigurationManager.ConnectionStrings["conndbprodnew"].ToString();
OracleConnection objconn = new OracleConnection(connStr);
string prop_name, tdc_property = "", qry = "";
qry = "SELECT CODE_DESC from tdc_product1 ";
OracleCommand objFetchCmd = new OracleCommand(qry, objconn);
List<GetCertificate> Certificate = new List<GetCertificate>();
objconn.Open();
OracleDataReader ReadData = objFetchCmd.ExecuteReader();
while (ReadData.Read())
{
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
}
return Certificate;
}
Where is the mistake i am trying like this but getting error at GetCertificate.ID .Any idea would be appreciated.
I guess you're making mistake at:
GetCertificate.ID = ReadData["ID"].ToString();
GetCertificate.CODE_DESC = ReadData["CODE_DESC"].ToString();
GetCertificate seems to be a type not a instance of object.
You should try something like:
Certificate.Add(new GetCertificate { ID = ReadData["ID"].ToString(), CODE_DESC = ReadData["CODE_DESC"].ToString() } );
Please be aware that I wrote this without any IDE, so there could be typo/syntax error, but you get the idea.
Small hint: Of course there're plenty of room for code refactor in your code (e.g. rename Certificate to Certificates), but that is another topic.

How to pass Array to MVC Controller with Jquery?

I am beginner to develope .Net MVC 5 application. But I have some problem with passing array or object to controller with Jquery.
I'm adding dynamically input fields with button. I want to pass input's data to controller. But I couldn't succeed.
Html Section is like that;
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='text' id='textbox1'>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
Get Value button function is like that;
$("#getButtonValue").click(function () {
var list = new Array();
for (i = 1; i < counter; i++) {
list[i] = $('#textbox' + i).val();
alert(list[i]);
}
var postData = { values: list };
$.ajax({
type: "POST",
url: "/Surveys/PostQuestionAndOptions",
data: postData,
success: function (data) {
alert(data);
},
dataType: "json",
traditional: true
});
});
Even I set "traditional" by true , the model is null.
[HttpPost]
public JsonResult PostQuestionAndOptions(string[] model)
{
return Json(true);
}
Could any one help me ? Thank you.
You need to have a strongly typed object.
JavaScript
$("#getButtonValue").click(function (e) {
e.preventDefault();
var list = [];
for (var i = 1; i < counter; i++) {
list.push($('#textbox' + i).val());
}
var postData = { values: list };
$.ajax({
type: "POST",
url: "/Surveys/PostQuestionAndOptions",
data: postData,
success: function (data) {
alert(data);
},
dataType: "json",
traditional: true
});
});
Strongly typed object
public MyValues {
public list<string> values {get; set;}
}
Controller method
[HttpPost]
public JsonResult PostQuestionAndOptions(MyValues model) {
return Json(true, JsonRequestBehavior.AllowGet);
}

Categories

Resources