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 ?
Related
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>
I have a drop down list and I want the value to be sent to the controller when an option is selected,replaceing the returned values in the desired inputs
Html Inputs :
<input type="text" class="form-control js-inputs" id="microchipcode">
<input class="form-control js-inputs" id="fa-horse">
<input type="text" id="fa-fatherhorse" class="form-control js-inputs">
Html DropDown:
$('.js-selected-item').change(function () {
let Value = $(this).val();
$.ajax({
data: { value: Value },
Url: "/Horse/GetHorseByMcode",
type: "post",
success: function (data) {
}
});
});
Controller :
public async Task<IActionResult> GetInfoHorse(string value)
{
var horse = await _coach.GetHorseByMcode(value);
if (horse != null)
{
return Json(horse);
}
return NotFound();
}
Query :
public async Task<Horse> GetHorseByMcode(string value)
{
return await _context.Horses.SingleAsync(h => h.MicrochipCode == value.Trim());
}
If you want to put a value into an input via js, add an ID to the inputs and do the following:
JS:
document.getElementById('//inputId').value = '';
Jquery:
("#//inputId").val("");
How do I access the data inside the object?
You can check the request and response in f12 developer tool Network tab, like below.
and implement frontend code to populate input field(s) in ajax success callback function based on your actual returned data.
For example:
success: function (data) {
$("#fa-fatherhorse").val(data.fatherHorse);
//populate other inputs based on your actual returned data
How to replace Drop Down list ?
If you want to dynamically set the selected value/option of the dropdown, you can try:
$("#dropdown_id_here").val(value_of_selected_option);
If you want to dynamically append <option> to your dropdown, you can try:
var newoption = "<option value='" + option_val + "'>" + option_text + "</option>";
$("#dropdown_id_here").append(newoption);
I have two dropdowns. One is for selecting the Main category, the second for selecting the sub category.
I want to be able to populate the sub category based on the Main category selected.
What I have tried so far is using JQUERY and AJAX to listen to change in the value of the dropdown using jquery and send an ajax request to the relevant route.
View
<div class="form-control">
<label for="category">Category</label>
<select name="category" id="category">
<option value='Men'>Men</option>
<option value='Women'>Women</option>
<option value='Sports'>Sports</option>
</select>
</div>
<div class="form-control">
<label for="subcategory">Sub Category</label>
<select id="subcategory" name="subcategory">
</select>
</div>
AJAX and JQUERY
$("#category").on("change", function () {
$("#subcategory").empty();
showValue($(this).val());
});
var data = {};
function showValue(val) {
console.log(val);
data.category = val;
$.ajax({
url: "/admin/update-list",
type: "POST",
data: data,
success: function(result) {
updateDOM(result);
},
error: function (err) {
console.log(err);
}
});
};
var updateDOM = function (result) {
var data = result.data;
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
$("#subcategory").append("<option>"+ data[i] +"</option>");
};
};
/admin/update-list Route
router.post('/update-list', (req,res,next) => {
let data = [];
let category = req.body.category;
console.log('From the ajax call, category is' + category);
if(category = "Men") {
data = [
'Sneakers',
'Boots',
'High Heels',
'Litas',
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Women") {
data = [
'Timbs'
];
res.status(200).json({data});
res.end();
}
else if(category = "Sports") {
data = [
'Soccer Boots',
'Rugby Boots'
];
res.status(200).json({data});
res.end();
}
});
No matter what option I choose, the second dropdown returns the same data.
I would do this in PHP. Hopefully this conveys what you could adapt to your situation:
<select name="foo" >
</select>
ajax call
$.ajax({
type:'POST',
url:'your_code_page.php',
data:'param1='+variable,
success:function(html){
$('[name="foo"]').html(html);
}
});
PHP post back
echo "<option value=''>Please select a thing</option>"; <<outside loop
while ($row = sqlsrv_fetch_array($results)) {
$value = $row['value'];
$display = $row['display'];
//-display the result of the array
echo "<option value= " . $value . ">" . $display . "</option>"; << options returned in post
}
I am trying to figure out how to get all the subjects of a specific year with ajax, jquery in Laravel.
I have three tables in database:
years: id, name
subjects: id, name
year_subject: id, year_id , subject_id
Here are the models:
Year.php
Subject.php
YearSubject.php
Here is the function in controller
public function get_subjects($id)
{
$sub = YearSubject::where("year_id", $id)->pluck("subject_id");
$subjects=Subject::where('$id',$sub)->pluck('name','id');
foreach($sub as $s)
{
$subjects= Subject::where('$id',$s)->pluck('name','id');
}
return json_encode($subjects);
}
<script type="text/javascript">
$(document).ready(function () {
$('#grade').on('change', function () {
var gradeID = $(this).val();
$('#subject').empty();
if (gradeID) {
$.ajax({
url: '{{url('get_subjects')}}' + '/' + gradeID,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, value) {
$('#subject').append('<option value="' + key + '">' + value + '</option>');
});
}
});
} else {
$('#subject').empty();
}
});
});
</script>
<select id="grade" name="grade" required>
<option value="" disabled selected> Choose Year</option>
#foreach($grades as $grade)
<option value="{{$grade->id}}">{{$grade->name}}</option>
#endforeach
</select>
<select name="subject" id="subject" >
<option value="">Choose Subject </option>
</select>
Here is the route
Route::get('get_subjects/{id}', 'SubjectController#get_subjects')->name('get_subjects');
I guess the error is at the controller. Can't figure out how to push values at $subjects.
Change your models to as shown below-
Year.php
class Year extends Model{
public $primaryKey = 'id';
public $timestamps = true;
protected $table = 'years';
public function subjects(){
return $this->belongsToMany('year_subject','year_id','subject_id');
}
}
Subject.php
class Subject extends Model{
public $primaryKey = 'id';
public $timestamps = true;
protected $table = 'subjects';
public function years(){
return $this->belongsToMany('year_subject','subject_id','year_id');
}
}
Your controller method:
public function get_subjects($year_id){
$subject_data = [];
foreach(Year::where('id',$year_id)->subjects() as $each_subject_data){
$subject_data[] = [
'subject_id' => $each_subject_data->id,
'subject_name' => $each_subject_data->name
];
}
return response(json_encode($subject_data),200)
->header('Content-Type','application/json');
}
NOTE: You can inspect element and check in network tab of your browser as to what JSON you are receiving and modify the JSON format you desire in controller method accordingly.
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)