Question : Laravel 9 return data for selected option in select with jquery
Answered by : laggs
-------------------------------------
// Controller
-------------------------------------
// Create a controller function.
public function datasum_per_school($id) { // Get the $id of the selected school. $school = School::find($id); // Make a check on any specifics you need to check. $registerd_learners = Learner::where('school_name', '=', $school->institution_name)->where('registered', '=', 'Yes')->count(); // Return the the view with all the variables needed. return view('admin.admin_componets.data_sum_per_school', [ 'school' => $school, 'registerd_learners' => $registerd_learners, ]); }
-------------------------------------
// Route
-------------------------------------
// Create a route, this is the url that will be used for a .load() function.
Route::get('/datasum/school/{id}', [DashboardController::class, 'datasum_per_school'])->name('datasum.school');
-------------------------------------
// Blade view for dashboard
-------------------------------------
// This is the page where the data will be displayed on.
@extends('admin.admin_dashboard')
@section('content')
<section id="content"> <div class="container clearfix mt-5"> <div class="row"> <div class="col-md-6 text-center mb-4"> // Create a <select> where you can can choose the spisific data. <select name="school_select" id="school_select" class="rounded"> @foreach ($schools as $school) // Use the id of the data as value. <option value="{{ $school->id }}">{{ $school->institution_name }}</option> @endforeach </select> </div> </div> <div class="row"> <div class="col-md-6"> // This is where the data will be displayed <div id="chart_holder_per_school"></div> </div> </div> </div>
</section>
// jquery cdn (version: 3.5.1)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
// Jquery script fuction to get and display the data
<script> $(document).ready(function () { refreshTable_school(); }); function refreshTable_school() { // Get the value from the <select> var school_id = $('#school_select').val(); // .load the url + the value of the <select> $('#data_holder_per_school').load('/datasum/school/' + school_id, function () { setTimeout(refreshTable_school, 5000); // <- Check data every 5 seconds, 1000 = 1 second. }); }
</script>
@endsection
-------------------------------------
// Blade view for data
-------------------------------------
// This page is where the data will be passed onto
<div class="row"> <div class="col-md-4"> <h5>Registered:</h5> </div> <div class="col-md-8 text-center"> // Return data gathered from controller <h1>{{ $registerd_learners }}</h1> </div>
</div>
Source : | Last Update : Thu, 01 Sep 22