I have a dropdown with values such as:
<select style="padding-top:300px;">
<form id="tram_stops">
<option onchange="tram_stops(this.value);" value="abraham-moss-tram">Abraham Moss tram stop</option>
<option onchange="tram_stops(this.value);" value="altrincham-tram">Altrincham tram stop</option>
<option onchange="tram_stops(this.value);" value="anchorage-tram">Anchorage tram stop</option>
and on change call ajax:
function tram_stops(tram_value) {
$.ajax({
url: '/tramsearch' + tram_value,
type: 'post',
dataType: 'html',
success: function(data) {
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
And controller:
public function tram_search($tram_value) {
$tram_text = $tram_value;
if ($tram_text) {
$client = new Client();
$crawler = $client->request('GET', 'https://beta.tfgm.com/public-transport/tram/stops/'.$tram_text);
echo "<div class=table-responsive><table class='table table-striped table-bordered table-hover'>";
$tfgm = $crawler->filter('table[id="departures-data"]')->each(function ($node) {
echo $node->html()."\n";
});
}
}
So what I want to achieve:
allow user to choose a tram stop. Value is a slug which is used in request('GET') in Controller. I then want to display data from that request and output it on the page.
As of this moment, when I choose an option from a dropdown, nothing happens.
Try doing like this :
<form id="tram_stops">
<select style="padding-top:300px;" onchange="tram_stops(this.value);" >
<option value="abraham-moss-tram">Abraham Moss tram stop</option>
<option value="altrincham-tram">Altrincham tram stop</option>
<option value="anchorage-tram">Anchorage tram stop</option>
</select>
</form>
Related
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.
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'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
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);
}
});
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.