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);
}
});
Related
Ajax code
$(function(){
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = new FormData(form.get(0));
$.ajax({
url: actionUrl,
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
...
},
error: function (message) {
alert(message);
}
})
})
}
In the partial view, I use select object #EmpSelect to add value and text to select object #RolesList, then use ajax post ID, Title, isVirtualGroup and RolesList to controller.
But the RolesList is always null, how can I do fix it?
javascript code
$('#AddRolesGroup').click(function () { $('#EmpSelect :selected').map(function (row, item) { console.log(item.text); $('#RolesList').append("<option value='" + item.value + "'>" + item.text + "</option>") }); });
View about select object part
<div id="area">
<select id="EmpSelect" class="form-select col-md-12" size="8"
multiple aria-label="EmpSelect">
</select>
<button class="btn" type="button" id="ClearSelect">Clear Select Roles</button>
<select asp-for="RolesList" asp-items="Model.RolesList" class="form-select col-md-12" size="8"
multiple aria-label="RolesList">
</select>
</div>
You need to make sure the select is in the form and make sure you have selected values.Here is a demo:
<form id="form1">
<div id="area">
<select id="EmpSelect" class="form-select col-md-12" size="8"
multiple aria-label="EmpSelect">
</select>
<button class="btn" type="button" id="ClearSelect">Clear Select Roles</button>
<select id="RolesList" name="RolesList" class="form-select col-md-12" size="8"
multiple aria-label="RolesList">
<option value="1">role1</option>
<option value="2">role2</option>
<option value="3">role3</option>
</select>
</div>
</form>
<button onclick="postdata()">postdata</button>
js:
function postdata() {
var sendData = new FormData($("#form1").get(0));
$.ajax({
url: "PostData",
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
//
},
error: function (message) {
alert(message);
}
})
}
action:
public IActionResult PostData(string[] RolesList)
{
return Ok();
}
result:
I want to generate a list on items in a drop down based on a previous choice from another select. All items ar in the database.
Here is what I did:
Javascript:
$(document).ready(function () {
$(document).on('change', '#province_name', function() {
var province_id = $(this).val();
var div = $(this).parent();
var op = " ";
$.ajax({
type: 'get',
url: '{!!URL::to('admin/findIDProvince')!!}',
data: {'id':province_id},
success: function(data){
for (var i = 0; i < data.length; i++){
op += '<option value="'+data[i].id+'">'+data[i].city_name+'</option>';
}
div.find('#city').html(" ");
div.find('#city').append(op);
},
error: function(){
console.log('success');
},
});
});
});
Routes (web.php):
Route::namespace('Admin')->prefix('admin')->middleware('auth', 'CheckAdmin')->group(function (){
$this->get('/findIDProvince', 'SchoolsListController#findIDProvince');
});
Controller (Admin/SchoolsListController.php):
public function findIDProvince(Request $request)
{
$data = City::select('name', 'id')->where('province_id', $request->id)->take(100)->get();
return response()->json($data);
}
HTML (view.blade.php)
<div class="form-group">
<label class="col-md-3" for="province_name">province_name</label>
<div class="col-md-9">
<select id="province_name" name="province_name" class="form-control col-md-12" required>
#foreach($province_names as $province_name)
<option value="{{ $province_name->id }}">{{ $province_name->province_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3" for="city_name">city_name</label>
<div class="col-md-9">
<select id="city_name" name="city_name" class="form-control col-md-12" required>
</select>
</div>
</div>
What am I doing wrong?
First, create a hidden filed with the value for which the option that need to be selected.
<input type="hidden" value="{{ $yourOptionValueToSelect }}" id="selectThis">
Then with jQuery find the matching value from your option and change the corresponding attribute as selected.
$('option').each(function() {
if (this.value == $('#selectThis').val()) {
this.setAttribute('selected', 'selected');
}
});
Example:
<input type="hidden" value="2" id="selectThis">
<select>
<option value="1">Hello</option>
<option value="2">World</option>
</select>
Here Option 2 will be selected by default with the above jQuery Code.
In your view it will be changed to:
<option value="2" selected="selected">World</option>
// prepend : attach default value to the begining of the dropdown for region
// $('.region').prepend('<option value="default" selected="selected">Please select</option>');
$('.region').on('change', function(e) {
$('.select2-selection__placeholder').css("font-size", '11px'); // change the font size of the select box
var region = e.target.value;
$.ajax({
url: "{{ url('/dropdown/station?region')}}=" + region, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data) {
// empty the option before we populate the dropdown
$('#station').empty();
// define default value
$('#station').append('<option value="default" selected="selected" disabled hidden></option>');
$.each(data, function(index, subCatObj) {
// alert(subCatObj.substation_name);
$('#station').append($('<option>').text(index).attr('value', index));
$('#station').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
});
$('.station').on('change', function(e) {
var station = e.target.value;
$.ajax({
url: "{{ url('/dropdown/kv-station?station')}}=" + station, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data) {
// empty the option before we populate the dropdown
$('#kvStation').empty();
// define default value
$('#kvStation').append('<option value="default" selected="selected" disabled hidden></option>');
$.each(data, function(index, subCatObj) {
// alert(subCatObj.substation_name);
$('#kvStation').append($('<option>').text(index).attr('value', index));
$('#kvStation').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
});
// kv station dropdown event
$('.kvStation').on('change', function(e) {
var station = e.target.value;
$.ajax({
url: "{{ url('/dropdown/ring?station') }}=" + station, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data, jqXHR) {
// remove the previous data ferom select
$('#ring').empty();
// checking the status code; if 204: no content, then
if (jqXHR.status === 204) {
$('#ring').append('<option value="default" selected="selected">No data</option>');
} else {
$('#ring').append('<option value="default" selected="selected" disabled hidden></option>');
}
// empty the option before we populate the dropdown
$.each(data, function(index, subCatObj) {
$('#ring').append($('<option>').text(subCatObj).attr('value', index));
$('#ring').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
// ring dropdown event
$('.ring').on('change', function(e) {
var id = e.target.value;
window.open('{{url(' / ring ')}}/' + id, '_blank');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="bottom">
<ul>
<li>
<label>Region
<select id="region-select" class=" form-control select2 region" name="region">
<option></option>
#foreach($regions as $region)
<option value="{{$region->region}}">
{{$region->region}}
</option>
#endforeach
</select>
{{-- {!! Form::select('region', $regions,'Please select ...', ['class' => 'region form-control select2', 'id' => 'region-select']) !!}--}}
</label>
</li>
<li>
<label>Station
<select id="station" class=" selectpicker station form-control input-sm" name="station">
<option value=""></option>
</select>
</label>
</li>
<li>
<label>KV Station
<select id="kvStation" class="kvStation form-control input-sm" name="kv-station">
<option value=""></option>
</select>
</label>
</li>
<li>
<label>Ring
<select id="ring" class="ring form-control input-sm" name="ring">
<option value=""></option>
</select>
</label>
</li>
</ul>
<i id="loading-image" hidden class="livicon" data-name="spinner-three" data-size="50" data-c="#fff" data-hc="#fff" data-loop="true"></i>
<div class="ajax-loader">
<img id="loading-image" class="loading-image img-responsive" src="{{ asset('images/ajax-loader.gif') }}">
</div>
</div>
I have the following script that sends a POST of my select option to a url called requestaccess. This works great when using only one of the two, but when I change the other field the result of the POST is None for the first and correct for the second and vice-versa.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control" id="accesslevelid" onclick="accesslevelid">
<option value=""> Please select your access level </option>
<option value="7"> Facility </option>
<option value="5"> Division </option>
<option value = "3"> Corporate </option>
<option value = "6"> Market </option>
<option value = "4"> Group </option>
</select>
<script>
$(document).ready(function () {
$('#accesslevelid').on('click', function () {
var accesslevelid = $(this).val();
$.ajax({ url: "{% url 'requestaccess' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
;
},
});
});
});
</script>
</div>
<div class="col">
<label for="phi"><h3>PHI</h3></label>
<select class="form-control" id="phi" title = "phi" onclick="phi">
<option value = ""> Please select if you need access to PHI data </option>
<option value = "0"> No </option>
<option value = "1"> Yes </option>
</select>
<script>
$(document).ready(function () {
$('#phi').on('click', function () {
var phi = $(this).val();
$.ajax({ url: "{% url 'requestaccess' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
},
type: 'POST',
success: function (result) {
;
},
});
});
});
</script>
My view gets the POST value with the following:
selectedaccesslevel = request.POST.get('accesslevelid')
print(selectedaccesslevel)
selectedphi = request.POST.get('phi')
print(selectedphi)
However, my print either displays as:
None
1 or 2
or
7, 5, 3, 6, 4
None.
My desired results are for it to display as :
7, 5, 3, 6, or 4
1 or 2
Maybe just write a single click function for both selects, ie each time you click on either of the selects you fetch both the select values and pass it to the view, something like this:
$(document).ready(function () {
$('.my_select').on('click', function () {
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid ').val();
$.ajax({ url: "{% url 'requestaccess' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid
},
type: 'POST',
success: function (result) {
;
},
});
});
});
do not forget to add class name 'my_select' to both your selects.
<select class="form-control my_select" id="phi" title = "phi" >
<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
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.
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) {
}
});
});