Im trying to add a live search in my project. searching the specified icons data when the key pressed trigger the ajax request.
but the problem is i trying to reuse the table wichis already use for placing the icons data using foreach. i get the data from a spesific method in my controller. so i need to replace the foreach data to placing ajax request data when key pressed to the same table.
the code is below
public function index()
{
$poseicons = Poseicon::paginate(5);
return view('config.config',['poseicons' => $poseicons]
);
}
public function search($request){
$poseicons = Poseicon::where('icons_id','%'.$request.'%')
->orwhere('name','%'.$request.'%')
->orwhere('icons','%'.$request.'%')
->get();
return $poseicons;
}
then this the is the table
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Icon</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach($poseicons as $poseicon)
<tr>
<th scope="row">{{$loop->iteration}}</th>
<td>{{$poseicon->icons_id}}</td>
<td>{{$poseicon->name}}</td>
<td><a href="/poseicon/{{$poseicon->icons_id}}" class="badge bg-info rounded-pill">Detail</a></td>
</tr>
@endforeach
</tbody>
</table>
then the ajax request
function fetchIconsSearch(){
let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
let search = document.getElementById('icons').value;
const url = `/metadata/search/${search}`;
fetch(url,
{
headers: {
"Content-Type": "application/json",
"Accept": "application/json, text-plain, */*",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-TOKEN": token,
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
},
method: 'get',
credentials: "same-origin"
})
.then(response => response.json()).then(response =>{
console.log(response);
//should i do foreach here then replace the value of the table?
//already try inserting data to the table. but the data become very messy because of the foreach.
}
)
}
so the conclusion is i want to know this is possible to do with vannila javascript and laravel.
if not possible please give me any alternative way to resolve this problem.
Thankyou, im very sorry about my very bad english,i hope this conveyed.
note:the ajax request work propperly.
question from:
https://stackoverflow.com/questions/65901432/replacing-the-value-of-blade-foreach-loop-using-fetch-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…