Jun 5, 2018
0
Level 11
displaying data from dynamic dropdown selection by using Laravel-jQuery Ajax calling
Hi Folks, I'm trying to display data from dynamic dropdown selection. I'm new to Laravel-jQuery Ajax Calling. I want to display books list by selecting author names from dropdown. How can I achieve that. any suggestions that would be appreciated. Looking forward Thanks in Advance.
//Blade.php
<link rel="stylesheet" href="{{ asset('css/home.css') }}" type="text/css"/>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<div class="container">
<div class="row col-md-12">
<div class="form-group col-md-12">
<label for="authorName">Select Author Name:</label>
<select name="authorName" id="authorName" class="form-control">
<option value="" disabled selected>Select Author Name</option>
@foreach($authors $author)
<option value="{{$author->id}}">{{ $author->id }} {{ $author->name }} </option>
@endforeach
</select>
</div>
</div>
<table class="table table-striped" id="table">
<thead>
<tr>
<th>Book ID</th>
<th>Location</th>
<th>Price</th>
<th>Start Date</th>
<th>End Date</th>
</tr>
</thead>
<tbody id="tbody">
@foreach($authorBooks as $authorBook)
<tr>
<td>{{$authorBook['id']}}</td>
<td>{{$authorBook['location']}}</td>
<td>{{$authorBook['price']}}</td>
<td>{{$authorBook['start_date']}}</td>
<td>{{$authorBook['end_date']}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<!-- Ajax Scripts -->
<script type="text/javascript">
$(document).ready(function() {
$('select[name="authorName"]').on('change', function() {
var authorID = $(this).val();
console.log(authorID );
if(authorID ) {
$.ajax({
url: '/authorsList/ajax/'+authorID ,
type: "GET",
dataType: "json",
$('#table').find('tbody').append([
'<tr>',
'<td>{{$authorBook['id']}}</td>',
'<td>{{$authorBook['location']}}</td>',
'<td>{{$authorBook['price']}}</td>',
'<td>{{$authorBook['start_date']}}</td>',
'<td>{{$authorBook['end_date']}}</td>',
'</tr>'
].join(''));
});
}
</script>```
//Controllers Code
public function authorsList() { $authors= Author::all();
return view('AuthorBooksList')->with(array('authors' => $authors));
}
public function authorBooksList($authorId)
{
$input = func_get_args($authorId);
$authorId= implode(' ', $input);
$authorBooks = \DB::table('books')
->leftJoin('authors', 'authors.id', '=', 'books.author_id')
->where(author_id', '=', $authorId)
->select('location', 'price', 'start_date', 'end_date')
->get();
return json_encode($authorBooks );
}
//Route.php
Route::get('authorsList',array('as'=>'authorsList','uses'=>'AuthorsController@authorsList'));
Route::get('authorsList/ajax/{id}',array('as'=>'authorsList.ajax','uses'=>'AuthorsController@authorBooksList'));
Please or to participate in this conversation.