Looking to incorporate a search bar into the bootstrap 4 modal header and utilize ajax GET request to retrieve and display search results in the modal body.
Although the request is successful, I'm having difficulty displaying the results in the modal.
https://i.sstatic.net/T4wHF.png
Seeking guidance on how to showcase the previewed results from the request in a modal.
Controller:
public function index()
{
....
//MODAL IS A PARTIAL ON THE INDEX PAGE
return view('friends.index',compact('friends','friendRequests'));
}
public function search(Request $request)
{
if ($request->has('name')) {
$name = $request->query('name');
$results = User::where('name','like','%'.$name.'%')->get();
} else {
$results = User::all();
}
//RETURNING THE MODEL PARTIAL,BUT WITH RESULTS
return view('layouts.partials.friends.modal',compact('results'));
}
Relevant routes:
Route::get('/friends','FriendsController@index')->name('friends');
Route::get('/friends/search','FriendsController@search')
->name('searchFriend');
Index view:
<div class="container my-5">
<div class="row">
<h4><i class="fas fa-user-friends"> Friends:</i></h4>
</div>
<div class="row">
<button type="button" class="btn btn-outline-success mx-auto btn-lg"
data-toggle="modal" data-target=".add-friends-modal">
Add new <i class="fas fa-user-plus"></i>
</button>
</div>
//MODAL PARTIAL IS INCLUDED HERE
@include('layouts.partials.friends.modal')
<hr>
@include('layouts.partials.friends.friends-list')
Modal partial:
<div class="modal fade add-friends-modal" tabindex="-1" role="dialog"
aria-labelledby="friends-modal" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header ">
<div class="container">
<div class="row">
<div class="col-6 offset-3">
<h5 class="modal-title text-center">Add new friend:</h5>
</div>
<div class="row mx-auto">
<form class="form-inline mt-4 mb-4" action="javascript:search();">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"
id="search-input">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">
<i class="fas fa-search"></i>
</button>
</form>
</div>
</div>
</div>
<button type="button" class="close pull-right" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
//RESULTS SHOULD BE DISPLAYED HERE
@if(isset($results) && count($results)>0)
<ul>
@foreach($results as $result)
<li>{{ $result->name }}</li>
@endforeach
</ul>
@endif
</div>
</div>
searchAJAX.js
function search() {
var userInput = document.getElementById("search-input").value;
var xhttp = new XMLHttpRequest();
xhttp.open('GET','/friends/search?name='+userInput,true);
xhttp.send();
}