ajax- pass dropdown option values as a list - ajax

i have a drop down list which allows multiple select like this:
<select id="myId" >
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
</select>
now on change the option i need to make an ajax call (to my controller) which sends the value of selected options
$("#myId").change(function(){
var myId= $("#myId").val();
$.ajax({
url:"${createLink(controller:'clientTrip',action:'fillData')}",
data: ({myId:myId}), // i want myid to be sent as list
dataType: "html",
success: function(data) {
}
});
});
i want to get value of myId as a list (list of selected option values) in my controller..
how can i do it? what changes i should make ?

You should most likely use the selected selector. Something like the following should work
$("#myId").change(function(){
var myIds = new Array();
$("#myId option:selected").each(function(){
myIDS.push($(this).val());
})
$.ajax({
url:"${createLink(controller:'clientTrip',action:'fillData')}",
data: ({myId:myIds}), // i want myid to be sent as list
dataType: "html",
success: function(data) {
}
});
});

Related

old() does not work on dependent dropdown in Laravel blade

I have two dropdown list in my Laravel page. I am trying to get old value of the dependent dropdown list (categorylist.blade) and make it selected once I fill and post the data. It returns back to the same page if the validation has not successfully completed. I am able to get all values except this one. I have tried Session::put() as well as Session::flash() but did not work. The category list is retrieved once you chose section as it requests the category list from the controller through ajax. How can I get the old value in the category dropdown list after the page refreshed.
Here is my section selection dropdown:
<select class="form-control sectionchoose" name="section_id" id="section_id">
<option value="">Choose Section</option>
#foreach($sections as $section)
<option value="{{$section['id']}}" #if(old('section_id') == $section['id']) selected #endif>{{$section['name']}} </option>
#endforeach
</select>
My categorylist dropdown:
<label class="col-sm-6">Chose Category</label>
<div class="categorylist">
#include('admin.deal-management.categorylist')
</div>
And this is my categorylist view file:
<select class="form-control " name="category_id" id="category_id">
<option value="">Choose Category</option>
#foreach($categories as $category)
<option value="{{$category['id']}}" #if(old('category_id') == $category['id']) selected #endif>
{{$category['category_name']}}
</option>
#endforeach
</select>
and this is my main controller:
public function addEditDeals(DealAddEditRequest $request, $id=null){
//*** post starts here ***/
if($request->isMethod('post')){
$message = 'Updated successfully';
$data=$request->all();
$deal->fill($request->validated());
$deal->save();
return redirect()->back()->with($message);
}
This is my categorylist controller:
public function findCategories(Request $request){
if($request->json()){
$data = $request->all();
$categories = Category::where(['section_id' => $data['id'], 'status'=>1])->get()->toArray();
return view('admin.deal-management.categorylist',compact('categories'));
}
}
And finally, this is the jQuery part:
$(document).ready(function (){
let sectionid = $('.sectionchoose').val();
$.ajax({
headers: {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
datatype: 'json',
url : '/admin/selectsection',
data: {id:sectionid},
success: function(response){
$('.categorylist').html(response)
}, error:function(){
}
})
})
Finally, I was able to find the solution. Whoever has the same issue can use the approach below:
Step 1: Send the Session value through the with() command:
return redirect()->back()->withErrors($validator)
->withInput()->with('cat_id',$data['category_id']);
}
Step 2: Retreive the data in your main blade and attain hidden input:
<input class="cat_id" id="asd" type="hidden" value="{{Session::get('cat_id')}}"/>
Step 3: Get the retreived session value in Jquery:
$(document).ready(function (){
let sectionid = $('.sectionchoose').val();
let cat_id;
if($('#asd').val()){
cat_id = $('#asd').val();
} else {
cat_id = 0;
}
$.ajax({
headers: {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
datatype: 'json',
url : '/admin/selectsection',
data: {id:sectionid, cat_id:cat_id},
success: function(response){
$('.categorylist').html(response)
}, error:function(){
}
})
})
Step 4: Send the session value to your dependent blade again (as cat_id here)
public function findCategories(Request $request){
if($request->json()){
$data = $request->all();
$cat_id = $data['cat_id'] ?? '';
$categories = Category::where(['section_id' => $data['id'], 'status'=>1])->get()->toArray();
return view('admin.deal-management.categorylist',compact('categories','cat_id'));
}
}
Done! As far as I know, there is not any other way to get old value of dependent dropdown list value so far.

How do I send and receive multiple selection values as ajax data?

The value of multiple selectable select tags is sent as ajax data and will be null.
html code
<select id="dd" class="selectpicker" multiple data-live-search="true" data-live-search-placeholder="Search" >
<optgroup label="filter1">
<option>option1</option>
<option>option2</option>
</optgroup>
<optgroup label="filter2">
<option>option1</option>
<option>option2</option>
</optgroup>
</select>
<select class="selectpicker" name ='start_y'>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
</select>
<select class="selectpicker" name ='end_y'>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
</select>
<button id ="go" type="button" class="btn btn-default">Search</button>
script
select tag value ajax
$(function(){
$('#go').click(function(){
var city = $('#dd').val();
var start_y = $('[name=start_y]').val();
var end_y = $('[name=end_y]').val();
$.ajax({
url: '/signUpUser',
data: {city:city,start_y:start_y,end_y:end_y},
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});
view
#app.route('/signUpUser', methods=['POST'])
def siii():
city = request.form.get("city")
start_y = request.form.get("start_y")
end_y = request.form.get("end_y")
return json.dumps({'city':city,'start_y':start_y,'end_y':end_y})
result
{"city":"null", "start_y":"2015", "end_y":"2016",}
Only select with multiple values ​​selected is null
???????
jQuery ajax uses PHP style serialization, meaning an array parameter will be posted with [] appended to it. To avoid this set traditional to true in the request.
$.ajax({
url: '/signUpUser',
data: {city:city,start_y:start_y,end_y:end_y},
type: 'POST',
traditional: true,
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});

Ajax not posting Select Option

I'm trying to get the value of the option in my template below called exampleid. I've followed several examples I found online, but nothing seems to work. My template below has the ajax and jquery to get the value but when I try to print it returns None. I've exhausted my resources and my professor doesn't seem to know, he's "looking into it".
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control" id="accesslevelid" onchange="accesslevelid" title="">
<option value="7"> Option 1</option>
<option value="5"> Option 2</option>
<option value = "3"> Option 3</option>
</select>
<script>
$(document).ready(function () {
$('#accesslevelid').on('change', function () {
var accesslevelid = $(this).val();
$.ajax({ url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
alert(result);
},
});
});
});
</script>
my view attempting to retrieve the value of the post.
exampleidpost = request.POST.get('accesslevelid', False)
print (exampleidpost)
My desired result is for the POST to return a 7,5, or 3.
You should add csrf token to you ajax request,
Try this way.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title="accesslevelid" class="form-control" id="accesslevelid" >
<option value="1"> Option1</option>
<option value="2"> Option2</option>
<option value="3"> Option3</option>
</select>
<script>
$(document).ready(function () {
$('#accesslevelid').on('change', function () {
var accesslevelid= $(this).val();
$.ajax({
url: "{% url 'submitted' %}",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {
accesslevelid: accesslevelid
},
type: 'POST',
success: function (result) {
alert(result);
},
});
});
});
</script>
And you no longer need a form.

Classic asp and ajax

I have problem with getting value from ajax to asp. I have form with select input field and if I select one option (from select options). I want to change my form action tag value.
$(document).ready(function() {
$("#preLin").change(function(){
if ($('#preLin option:selected').val() === "Test" ) {
var actionTag = "printHosp.his";
$.ajax({
type: "POST",
url: "http://local:8001/Default.his",
data: {actionTag: "test.asp"},
success: function(data) {
alert(actionTag);}
});
});
ASP
dim actionTag
actionTag = Request.form("actionTag")
<form action="<%=actionTag%>" name="input" method="post" target="_blank">
<select name="preLin" id="preLin">
<optgroup >
<option value="Test"></option>
<option value=""></option>
</optgroup>
</form>
There's best practices to do what you want, but i suggest you to solve this problem by adding a "ajax error function", then analyzing the responseText.
Change your ajax call for something like:
$.ajax({
type: "POST",
url: "http://eli.local:8001/priemimas/Default.his",
data: {actionTag: "test.asp"},
success: function(data) {alert(actionTag);},
error: function(xhr) {alert(xhr.responseText);}
});

Setting the selected item in a selectlist after ajax callback

I am updating a selectlist element using a jquery ajax callback in a mvc application when another selectlist is changed.
The ajax callback calls an action that returns a partialview.
The partialview is then set as the content of a div.
The problem is that when the partialview is returned it has the wrong item set as selected so i need a way to set the selected item following the callback.
$(document).ready(function () {
$("#DependentDropDownValue").change(function () {
var selected = $("#DropDownValue").val();
var data = {data: $("#DependentDropDownValue").val()};
$.ajax({
url: "#Url.Action("IndexPartial","DropDown")",
data: data,
success: function (x) {
$("#partialDiv").html(x);
$("#DropDownSelectList").val(selected);
}
});
});
});
x has the content:
"<select id="DropDownValue" name="DropDownValue">
<option value="1">Emne11</option>
<option value="2">Emne12</option>
<option value="3">Emne13</option>
<option value="4">Emne14</option>
<option value="5">Emne15</option>
<option selected="selected" value="0">-------</option>
<option value="6">Emne21</option>
<option value="7">Emne22</option>
<option value="8">Emne23</option>
<option value="9">Emne24</option>
<option value="10">Emne25</option>
</select>"
The variable "selected" contains the value of the selected option before the callback.. that item has to be set as selected again.
I have tried using
$("#DropDownSelectList").val(selected);
but that doesnt seem to work
The id of the select list that you have shown is DropDownValue and not DropDownSelectList, so make sure that you are using the correct id in your script:
$('#DropDownValue').val(selected);

Resources