I'm trying to implement a live search bar. Live search is working, but it prints the output twice, which is annoying. Could you please take a look at where the problem lies? Thanks.
This is my search function code.
public function search(Request $request) { if ($request->ajax()) { $output = ""; $projects = Project::where('title', 'LIKE', '%' . $request->search . '%') ->where('module_code',$request->module_code) ->get(); $count = count($projects); // $projects = array_unique($projects); if ($projects) { foreach ($projects as $project) { $output .= '<tr>' . '<td>' . $project->team_number . '</td>' . // '<td>' . $count . '</td>' . '<td>' . $project->lab . '</td>' . '<td>' . '<a href="/projects/' . $project->id . '" style="display:block;"><b>' . $project->title . '</b></a>' . '</td>' . '<td>' . $project-> latest_state. '</td>' . '<td>' . $project->team_member_1 . '</td>' . '<td>' . $project->latest_team_member_1_state . '</td>' . '<td>' . $project->team_member_1 . '</td>' . '<td>' . $project->latest_team_member_1_state . '</td>' . '<td>' . $project->team_member_1 . '</td>' . '<td>' . $project->latest_team_member_1_state . '</td>' . '<td>' . $project->ta . '</td>' . '<td>' . $project->created_at . '</td>' . '<td>' . '<button class="btn-sm btn-info pull-left" onclick="location.href = \'/projects/' . $project->id . '\'">Project Details</button> ' . '</td>' . '</tr>'; } return Response($output); } } }
This is the script to do a live search in php Blade:
<script type="text/javascript"> const getQueryParams = (params, url)=>{ let href = url; let regexp = new RegExp('[?&]' + params + '=([^&#]*)', 'i'); let qString = regexp.exec(href); return qString ? qString[1] : null; } $('#search').on('keyup',function(){ $value = $(this).val(); //alert($value); $qString = getQueryParams('module', window.location.href); $queryString = $.ajax({ type : 'get', url : '{{URL::to('search')}}', data : {'search':$value, 'module_code', $qString}, success:function (data) { //console.log(data); //alert(data); $('tbody').html(data); } }); }) </script>
This is the code for the search bar in php Blade
<div class="col-sm-5"> <input type="text" class="form-control" id="search" name="search" placeholder="Search..."/> </div>
Before searching:
After searching:
Damn, I just found out what was causing this problem. This is a bit silly. The original code is here: https://onecompiler.com/posts/3xy39rm78/php-blade-for-staff and the error still exists. The problem is, I added an unnecessary additional tag. The output is placed in labeled places, just like the script:
At the last point of the code, it tells the html to print the result at the tag (I'm not sure if this is correct). By removing the attached tbody tag, the problem was solved.