Two Ajax calls only meet one condition at a time - ajax

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">

Related

how send id in ajax for laravel

i want to run my ajax after click on one of the options in select tag. and send id of option to ajax url.
please help me . these are my codes.
#foreach($emails as $mail)
<option id="{{$mail->id}}">{{$mail->email}}</option>
#endforeach
</select>
my ajax
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.select option').on('click',function () {
var id=$('.select option:selected').attr("id");
$.ajax({
url:'/mailactive',
type:'get',
dataType:'json',
data:{id:id}
})
})
})
try to use this:
give to your select an id, for example id_select
use #id_select > option:selected in your jQuery selector instead of .select option:selected
then tell me if you still can't get the id
In Your Laravel Blade
<select id="email">
#foreach($emails as $mail)
<option id="{{ $mail->id }}"> {{ $mail->email }} </option>
#endforeach
</select>
If your Route is POST method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.post('{{ url('your_POST_route_url') }}', {
'_token': "{{ csrf_token() }}", id:id,
}, function (data) {
console.log(data); // Print your response into your console
});
});
If your Route is GET method
$(document).ready(function () {
var id = $('#email').children(":selected").attr("id");
$.get('{{ url('your_GET_route_url') }}', {
id:id,
}, function (data) {
console.log(data); // Print your response to your console
});
});
You should have return data from your GET or POST method.

Laravel 5 multi dynamic dropdown

I'm trying to use the data of the first dropdown, to fill the second.
An example here:
https://gitlab.com/Bons/laravel5.3_dynamic_dropdown/blob/master/readme.md
Controller functon return data, but second dropdown is empty.
First dropdown:
<span>Country: </span>
<select style="width: 200px" class="country" id="id_country">
<option value="0" disabled="true" selected="true">-Select-</option>
#foreach($countries as $contry)
<option value="{{$contry->id_country}}">{{$contry->name}}</option>
#endforeach
</select>
linked dropdown:
<label>City
<select id="region" class="form-control input-sm" name="region_id">
<option value=""></option>
</select>
</label>
Script:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.country',function(){
console.log("hmm its change");
var id=$(this).val();
console.log(id)
$.ajax({
type:'get',
url:'{!!URL::to('findRegions')!!}',
data:{'id':id},
success:function(data) {
console.log("success");
console.log(data.length);
console.log(data);
$.each(data, function(index,subCatObj){
// console.log(subCatObj.name)
$('#region').append(''+subCatObj.name+'');
});
},
error:function(){
console.log("error");
}
});
});
});
</script>
Route:
Route::get('/findRegions/','GirlsController#findRegions');
Controller function:
public function findRegions(Request $request){
$id=$request->id;
$regions=Region::select('name')
->where('id_country',$id)
->get();
dump($regions);
return $regions;
}
Here is how i did it,
in routes/web.php
Route::post('select-ajax', 'Main#selectAjax')->name('select-ajax');
in Controller : Main.php
public function __construct()
{
View::share('selectAllCountries', Country::pluck("name","id")->all());
}
public function selectAjax(Request $request)
{
if($request->ajax())
{
$getRegion = Region::where('id_country',$request->id)->pluck("nameOfTheRegion","id")->all();
$data = view('ajax-select',compact('getRegion'))->render();
return response()->json(['options'=>$data]);
}
}
then create a simple blade file name ajax-select.blade.php
<option selected disabled>--- Select Region---</option>
#if(!empty($getRegion))
#foreach($getRegion as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
#endif
Ajax call
{!! Form::select('country',[' '=>'--- Select Country ---']+$selectAllCountries,null,['class'=>'form-control']) !!}
{!! Form::select('region',[' '=>'--- Select Region---'],null,['class'=>'form-control']) !!}
<script>
$("select[name='country']").change(function(){
var id = $(this).val();
var token = $("input[name='_token']").val();
$.ajax({
url: "{{ route('select-ajax') }}",
method: 'POST',
data: {'id':id, '_token':token},
success: function(data) {
$("select[name='region']").html('');
$("select[name='region']").html(data.options);
},
error:function(){
alert("error!!!!");
}
});
});
</script>
Hope this helps

How to create drop down

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>

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.

Resources