I have:
{{ Form::select("toLeague",$select_leagues,null, ['class' => 'selectpicker']) }}
I want to do each league in $select_leagues as a link with it's id like:
<a href="league/albums/{league->id}">
How to do this?
You need use onchange javascript event and redirect
$(document).ready( function() {
$('#idSelect').change( function() {
location.href = 'league/albums/'+$(this).val();
});
});
Or using jquery:
$('#idSelect').bind("change keyup",function()
{
window.location = 'league/albums/'+$(this).val();
});
Related
I know there's other topic on this in stackoverflow but it still didn't work for me. I try to make a simple dynamic menu that generate dynamic content based on the chosen <li> id.
This is the code to generate the menu :
foreach($cabang as $index=>$model){
echo '<li id='.$model->idDpd->id_dpd.'>
<a class="nav-link" href="#" role="tab" data-toggle="tab">'.$model->idDpd->dpd.'</a>
</li>';
}
The menu is created successfully. But I have the problem with the content generated with Ajax
This is what I have in my view file :
$script = <<< JS
$(document).ready(function(){
function load_page_details(id)
{
$.ajax({
url: "<?=Url::to(['/site/fetch']) ?>",
method:"POST",
data:{id:id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success:function(data)
{
$('#page_details').html(data);
}
});
}
//load page-details where the id in the database table equals 1. Set the default to 1 while page is loading for the first time.
/* load_page_details(1);*/
$('.nav li').click(function(){
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script)
?>
This is my SiteController and the action :
public function actionFetch(){
if (Yii::$app->request->isAjax) {
// fetch the $_POST["id"]
$data = Yii::$app->request->post('id');
if(isset($data))
{
$query= Cabang::find()->where(['id_dpd'=> $data])
->joinWith('idDpd')
->all();
$output = '';
foreach($query as $model)
{
$output .= '
<div role="tabpanel" class="col-lg-4 tab-pane fade show active" >
<div class="col-md-12">
<h4>'.$model->kota.'</h4>
<p>'.$model->alamat.'</p>
<p>'.$model->telp.'</p>
<p>'.$model->email.'</p>
<p>'.$model->jadwal.'</p>
</div>
</div>
';
}
/* echo $output;*/
// return Json
return \yii\helpers\Json::encode($output);
}
}
}
The error caught in my console in chorome dev tool : jquery.js:9175 POST http://localhost/%3C?=Url::to([%27/site/fetch%27])%20?%3E 403 (Forbidden)
I tried to make the fetch function to a new php file and link the URL in my Ajax to that file (not to a controller or SiteController in my case) like : url: url:"site/fetch.php",but it returned jquery.js:9175 POST http://localhost/site/fetch.php 404 (Not Found)
What am I doing wrong? I have spent two days without solution. Thanks for the help!
Your PHP is not correct - you cannot use <?= /* ... */ ?> inside of heredoc. You need to use temporary variable:
$url = Url::to(['/site/fetch']);
$script = <<<JS
$(document).ready(function () {
function load_page_details(id) {
$.ajax({
url: "$url",
method: "POST",
data: {id: id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success: function (data) {
$('#page_details').html(data);
}
});
}
$('.nav li').click(function () {
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script);
I want to create advance search filtering staff data according to certain criteria chosed by users. This application developed using laravel 5. I am querying the data using ajax function and if statement to filter the criteria. The results appear but it does not filter any condition in the if statement.
The controller of the filtering condition is this:
public function kakitangan(Request $request)
{
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if ($request->section != ""){
$query->where('SectionID', $request->section);
}
$newitem = $query->get();
return response::json($newitem);
}
I also have tried this:
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if(request('section')) {
$query->where('SectionID', request('section'));
}
$newitem = $query->get();
return response::json($newitem);
But the result is the same..all data in itemregistrations appear in the output page. Although I select another section criteria.
This is the view page code for selection:
<div class="row">
<div class="col-lg-2">
{{ Form::label('Seksyen', 'Seksyen') }}
</div>
<div class="col-lg-2">
{{ Form::select('section', $sections, '', ['class' => 'form-control select2', 'placeholder' => '--pilih--']) }}
</div>
</div>
</div>
The selection id is from controller function:
$sections = Section::pluck('sectionname', 'SectionID');
//sent to html view
return view('carian.index', compact('sections'));
Button to call ajax function to get the query:
<button class="btn btn-primary btn-md" id="cari">Cari</button>
The code for results appear:
<script type="text/javascript">
$( "#cari" ).click(function() {
var seksyen = $("#section").val();
$.ajax({
url: '{{ url('kakitangan') }}',
data: {'section': seksyen},
dataType: 'json',
success: function (data) {
console.log(data);
$('#datatable tr').not(':first').not(':last').remove();
var html = '';
for(var i = 0; i < data.length; i++){
html += '<tr>'+
'<td>' + data[i].name + '</td>' +
'</tr>';
}
$('#datatable tr').first().after(html);
},
error: function (data) {
}
});
});
</script>
Should be when the user select a section, only staffs of the section appear. But now all staffs appear when select any section.
I just tried to test whether the section value is correctly passed to the controller using this in controller:
$try=$request->input('section');
return response::json($try);
It results empty array..no value passed? Is it the section value is not passed correctly? How to correct this problem?
You are passing the section as a post param while you performing a GET request.
Using jQuery you can send this as a query string using:
var seksyen = $("#section").val();
$.ajax({
url: '{{ url('kakitangan') }}?' + $.param({'section': seksyen}),
dataType: 'json',
...
In your controller you can also explicitly check if a request contains a query string using the has method on a request
if(request()->has('section')) {
$query->where('SectionID', request('section'));
}
EDIT:
using the laravel collective Form helpers you can specific the field id using the following (note the fourth argument id)
{{ Form::select('section', $sections, '', ['id' => 'section', 'class' => 'form-control select2', 'placeholder' => '--pilih--']) }}
Hello I need to do autocompletion to some cities i already have in my db
so my code is like this :
View
<input type="text" name="ville" id="ville" class="small" placeholder="Entrer la ville souhaité">
<script type="text/javascript">
$(function() {
$( "#ville" ).autocomplete({
source:'{!!URL::route('autocomplete')!!}',
minlength:1,
autoFocus:true,
select:function(e,ui)
{
$('#ville').val(ui.item.value);
}
});
});
</script>
Controller
class VilleController extends Controller
{
public function autocomplete(Request $request)
{
$term = $request->term;
$queries = DB::table('ville')
->where('libelle_ville', 'like', '%'.$term.'%')
->take(6)->get();
foreach ($queries as $query)
{
$results[] = ['id' => $query->id, 'value' => $query->libelle_ville]; //you can take custom values as you want
}
return response()->json($results);
}
}
Routes
Route::get('/autocomplete', array('as' => 'autocomplete', 'uses'=>'VilleController#autocomplete'));
It doesn't tells me that I have an error and it doesn't show me any completion either.
Debug json request with laravel is a bit difficult, I recommend you to download this package
https://github.com/ARCANEDEV/LogViewer
or manually open the laravel log in storage/logs/laravel.log and see whats happened
Thanks to Stack and EddyTheDove I found out that the error is that aucomplete is not a function so I have to remove the barkets and $function so it would be something like this in the script tag
<script type="text/javascript">
$( "#ville" ).autocomplete({
source:'{!!URL::route('autocomplete')!!}',
minlength:1,
autoFocus:true,
select:function(e,ui)
{
$('#ville').val(ui.item.value);
}
});
</script>
I am using Laravel 5.3 and vue.js 2.0,
And I use axios (https://github.com/mzabriskie/axios) to send ajax requests,
I follow the docs to set the TOKEN like this:
<script>
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; //The error is at this line.
new Vue({
el: "#app",
data: function () {
return {
items: []
}
},
mounted: function () {
this.$nextTick(function () {
axios.get('/articles').then(function (response) {
response.data.forEach(function (item) {
item.selected = false;
});
this.items = response.data;
}).catch(function (error) {
console.log(error);
});
});
}
});
</script>
the error in console is like this:
Uncaught ReferenceError: AUTH_TOKEN is not defined
What should I do?
have you set AUTH_TOKEN on the window? If not window.AUTH_TOKEN will naturally not be defined.
A common set up in the head of a laravel app is:
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
This would therefore set the csrf token. I wouldn't imagine this is how you'll be setting an Auth token so you'll probably just need to look into why you are calling window.AUTH_TOKEN
In terms of how you generate your token that is dependant on what type you require but once you have it you may want to look instead at vuex for storing it. Doing so will allow you access to it throughout your app, without having to store anything on the window.
it should be
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
and you can remove the
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
part
I've read both https://gist.github.com/tobysteward/6163902 & AJAX pagination with Laravel but it seems I have a different problem so anyway.
Long story short: When I search, the right data gets fetched and the ajax works "display data, no refresh" only for the first page, but from next page on the page refreshes, so how to make an ajax call that loop through the returned data and display it according to each page?
Also how to add the search query to the URL, currently when the data gets fetched, the URL doesn't update, instead it stays on its current state (i.e. index?page=3).
search form
{{ Form::open(['route' => 'search', 'method' => 'GET', 'id' => 's-form',])}}
{{ Form::text('search', null, ['id' => 'search', 'placeholder' => 'Search For ...']) }}
{{ Form::submit(Go) }}
{{ Form::close() }}
search controller
public function search() {
$input = Input::get('search');
$posts = Post::where('title','LIKE',$input)->paginate(4);
if (Request::ajax()) {
return View::make('posts.search')->withPosts($posts);
}
return View::make('posts.index')->withPosts($posts);
}
search view
#forelse ($posts as $post)
// do stuff
#endforeach
<nav>{{ $posts->appends(Request::except('page'))->links() }}</nav>
the js
$('#s-form').submit(function(e)
{
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
data:{
search: $('#search').val()
},
success: function(data){
$('#result').html(data);
}
});
});
This is all it needed:
$(document).ajaxComplete(function() {
$('.pagination li a').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data) {
$('#result').html(data);
}
});
});
});
Now I just need to update the URL according to each page.