I'm using Laravel and in my controller I'm getting data from external API. So far I can successfully get the data and looping into select drop down.
Because of the large data I want to fetch this result only when a user clicks on a specific radio button, instead of every time when that page is loaded.
How can I fetch the data using AJAX?
Here's my code bellow:
Checkout Controller:
public function offices(Request $request) {
$url = Http::get('the_url_of_the_api', [
'userName' => '123456',
'password' => '345678',
]);
$response = json_decode($url);
$offices = $response->offices; // this is the variable I get successfully and I loop in the code bellow
}
View
<select name="office" class="offices form-control">
@foreach($offices as $office)
<option value="{{ $office->name }}">{{ $office->name }}</option>
@endforeach
</select>
Now I'm trying to get that data with AJAX, so I've created a route and Javascript bellow.
Route:
Route::get('/offices', 'App\Http\Controllers\CheckoutController@offices')->name('offices');
Javascript:
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('input[name="radio"]').click(function(){
$.ajax({
type: "GET",
url: "/offices",
data: '',
success: function() {
// How can I fetch that variable offices from the controller and loop inside the select drop down box?
}
});
});
});
</script>
Route::get(...). Furthermore, your question is about jQuery (and perhaps javascript). Not about php and Laravel. I suggest you remove those two tags. And finally a suggestion for your problem: try aconsole.logof the response you get in the success function. The jQuery doc will tell you more on how to include that response into the function.