Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Dennys's avatar

Live search in Laravel 5.8 using AJAX doesn't show results in the table

Hello,

following a guide found on the web I developed a table which show data from a database and a live search bar which filter the results on the table, the problem is that it doesn't show any result (even without typing in the search bar).

I've been trying to solve the problem for hours without success. Can someone help me please?

Many thanks in advance.

This is my view:

@extends('layouts.app')

@section('content')

    @push('head')
        <script>
            $(document).ready(function () {

                fetch_customer_data();

                function fetch_customer_data(query = '') {
                    $.ajax({
                        url: "{{route('formatore.utenti.action')}}",
                        method: 'GET',
                        data: {query: query},
                        dataType: 'json',
                        success: function (data) {
                            $('tbody').html(data.table_data);
                        }
                    })
                }

                $(document).on('keyup', '#search', function () {
                    var query = $(this).val();
                    fetch_customer_data(query);
                });
            });
        </script>
    @endpush


    <div class="container" xmlns="http://www.w3.org/1999/html">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Lista utenti</div>
                    <div class="card-body">
                        <div class="form-group">
                            <input type="text" name="search" id="search" class="form-control"
                                   placeholder="Cerca utenti" />
                        </div>
                        <div class="table-responsive">
                            <table class="table table-striped table-hover table-sm">
                                <thead>
                                <tr>
                                    <th>Nome</th>
                                    <th>Cognome</th>
                                    <th>Settore</th>
                                    <th>Località</th>
                                    <th>Data di nascita</th>
                                    <th>Telefono</th>
                                    <th>Cellulare</th>
                                    <th>Email</th>
                                </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                        <a href="{{ route('formatore.dashboard') }}">
                            <button type="button" class="btn btn-secondary btn-lg btn-block">Torna alla home</button>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

This is the controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UtentiController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:formatore');
    }

    public function index()
    {
        return view('utenti');
    }

    function action(Request $request)
    {
        if ($request->ajax()) {
            $output = '';
            $query = $request->get('query');
            if ($query != '') {
                $data = DB::table('users')
                    ->select('nome','cognome','settore','indirizzo_localita','data_nascita','telefono','cellulare','email')
                    ->where('nome', 'like', '%' . $query . '%')
                    ->orWhere('cognome', 'like', '%' . $query . '%')
                    ->orWhere('settore', 'like', '%' . $query . '%')
                    ->orWhere('indirizzo_localita', 'like', '%' . $query . '%')
                    ->get();
            } else {
                $data = DB::table('users')
                    ->select('nome','cognome','settore','indirizzo_localita','data_nascita','telefono','cellulare','email')
                    ->orderBy('created_at', 'desc') //creared at non ce nella select
                    ->get();
            }
            $total_row = $data->count();
            if ($total_row > 0) {
                foreach ($data as $row) {
                    $output .= '
                    <tr>
                    <td>'. $row->nome.'</td>
                    <td>'. $row->cognome.'</td>
                    <td>'. $row->settore.'</td>
                    <td>'. $row->indirizzo_localita.'</td>
                    <td>'. $row->data_nascita.'</td>
                    <td>'. $row->telefono.'</td>
                    <td>'. $row->cellulare.'</td>
                    <td>'. $row->email.'</td>
                    </tr>
                    ';
                }
            } else {
                $output .= '
                <tr>
                <td align="center" colspan="5">
                Nessun dato trovato
                </td>
                </tr>
                ';
            }
            $data = array(
                'table_data' => $output
            );
            echo json_encode($data);
        }
    }
}

These are the routes: (the last 2 are about the live search page)

<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Auth::routes([
    'register' => false,
    'verify' => false,
    'reset' => false
]);

Route::get('/home', 'HomeController@index');

Route::prefix('formatore')->group(function (){
    Route::get('/login', 'Auth\FormatoreLoginController@showLoginForm')->name('formatore.login');
    Route::post('/login', 'Auth\FormatoreLoginController@login')->name('formatore.login.submit');
    Route::get('/', 'FormatoreController@index')->name('formatore.dashboard');
    Route::get('/h', 'HController@index')->name('formatore.h');
    Route::get('/q', 'QController@index')->name('formatore.q');
    Route::get('/utenti', 'UtentiController@index')->name('formatore.utenti');
    Route::get('/utenti/action', 'UtentiController@action')->name('formatore.utenti.action');
});

The columns of the "users" table are "id_utente", "id_formatore", "nome", "cognome", "sesso", "indirizzo_titolo", "indirizzo_via", "indirizzo_cap", "indirizzo_localita", "settore", "data_nascita", "stato_civile", "num_avs", "nazionalita", "permesso", "iban", "telefono", "cellulare", "email", "email_verified_at", "password", "attivo", "remember_token", "id_colloquio", "created_at" and "updated_at"

0 likes
7 replies
jlrdw's avatar

I see you are using

 echo json_encode($data);

In Laravel I usually use:

return Response::json($data);

Don't forget to have the use statement:

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
1 like
Dennys's avatar

Thanks for your help, appreciated. But unfortunately the problem persists despite the corrections.

imawesome's avatar

Did you inspect the response of AJAX query inside the Developer Tools? Does variable $output contain what you want?

1 like
Sibey's avatar

I think I followed the same guide as you. I also have the same problem like u. How exactly did u fix it? Thanks in advance.

Dennys's avatar

Hello, sorry for the late reply, I will post my working solution:

The controller:

function action (Request $request)
    {
     
            if ($request->ajax()) {
                $output = '';
                $query = $request->get('query');
                if ($query != '') {
                    $data = DB::table('users')
                        ->join('dati_percorso', 'users.id_utente', '=', 'dati_percorso.id_utente')
                        ->select('users.email', 'users.nome', 'users.cognome', 'users.password_in_chiaro', 'users.attivo', 'dati_percorso.inizio')
                        ->where('users.attivo', 'like', '%' . '1' . '%')
                        ->where('users.nome', 'like', '%' . $query . '%')
                        ->orWhere('users.cognome', 'like', '%' . $query . '%')
                        ->orderBy('dati_percorso.inizio', 'desc')
                        ->get();
                } else {
                    $data = DB::table('users')
                        ->join('dati_percorso', 'users.id_utente', '=', 'dati_percorso.id_utente')
                        ->select('users.email', 'users.nome', 'users.cognome', 'users.password_in_chiaro', 'users.attivo', 'dati_percorso.inizio')
                        ->where('users.attivo', 'like', '%' . '1' . '%')
                        ->orderBy('dati_percorso.inizio', 'desc')
                        ->get();
                }
                $total_row = $data->count();

                if ($total_row > 0) {
                    foreach ($data as $row) {

                        $inizio = Carbon::parse($row->inizio)->format('d.m.Y');
                        $output .= '
                    <tr>
                    <td>' . $row->nome . '</td>
                    <td>' . $row->cognome . '</td>
                    <td>' . $row->email . '</td>
                    <td>' . $row->password_in_chiaro . '</td>
                    <td>' . $inizio . '</td>
                    </tr>
                    ';
                    }
                } else {
                    $output .= '
                <tr>
                <td align="center" colspan="5">
                Nessun utente trovato, importa i dati.
                </td>
                </tr>
                ';
                }
                $data = array(
                    'table_data' => $output
                );
                echo json_encode($data);
            }
        }

The view:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

@extends('layouts.app')
@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-10">
                <h2>Lista dati di accesso degli utenti</h2>
            </div>
        </div>
        <div class="form-group">
            <input type="text" name="search" id="search" class="form-control"
                   placeholder="Cerca utenti"/>
        </div>
        <div class="table-responsive">
            <table class="table table-hover table-sm">
                <thead>
                <tr>
                        <th>Nome</th>
                        <th>Cognome</th>
                        <th>Email</th>
                        <th>Password</th>
                        <th>Attivo dal</th>
                 
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
        </br>
        <a href="{{ route('formatore.dashboard') }}">
            <button type="button" class="btn btn-secondary btn-lg btn-block">Torna alla home</button>
        </a>
    </div>

    <script>
        $(document).ready(function () {

            fetch_customer_data();

            function fetch_customer_data(query = '') {
                $.ajax({
                    url: "{{route('formatore.listapassword.action')}}",
                    method: 'GET',
                    data: {query: query},
                    dataType: 'json',
                    success: function (data) {
                        $('tbody').html(data.table_data);
                    }
                })
            }

            $(document).on('keyup', '#search', function () {
                var query = $(this).val();
                fetch_customer_data(query);
            });
        });
    </script>
@endsection

I hope it will help.

andrydox's avatar

i have same problem too, im using laravel 7, please advice : here is my controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LivesearchController extends Controller
{
    public function indexing()
	{
		return view('pages.evaluation.eval-search');
	}
function search(Request $request)
	{
		if($request->ajax())
		{
			$output = '';
			$query = $request->get('query');
			if($query != '')
			{
				$data = DB::table('department')
					->where('name', 'like', '%'.$query.'%')
->get();
			}
			else
			{
				$data = DB::table('department')
					->orderBy('emp_id', 'desc')
					->get();
			}
				$total_row = $data->count();
if($total_row > 0)
				{
					foreach($data as $row)
					{
						$output .=
							'<tr>
								<td>'.$row->id.'</td>
								<td>'.$row->emp_id.'</td>
								<td>'.$row->name.'</td>
								<td>'.$row->dept.'</td>
								<td>'.$row->sec.'</td>
								<td>'.$row->subsec.'</td>
								<td>'.$row->group.'</td>
								<td>'.$row->subgroup.'</td>
							</tr>';
					}
				}
				else
				{
					$output .= 
						'<tr>
							<td align="center" colspan="5"> No Data Found</td>
						</tr>';
				}
				$data = array(
					'table_data' => $output,
					'total_data' => $total_row
					);
				return Response::json($data);

view :

@extends('layouts.app')

@section('content')
@push('scripts')
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
	<script>
		$(document).ready(function(){

 fetch_customer_data();

 function fetch_customer_data(query = '')
 {
  $.ajax({
   url: "{{route('pages.evaluation.search')}}",
   method:'GET',
   data: {query: query},
   dataType: 'json',
   success: function(data)
   {
    $('tbody').html(data.table_data);
    $('#total_records').text(data.total_data);
   }
  })
 }

 $(document).on('keyup', '#search', function(){
  var query = $(this).val();
  fetch_customer_data(query);
 });
});
	</script>
@endpush
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">{{ __('Dashboard') }}</div>

                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    <div class="card-body">
						<h4 class="card-title">Search Employee</h4>
						<div class="form-group">
							<input type="text" name="search" id="search" class="form-control" placeholder="type id pegawai" />
						</div>
						<div class="table-responsive">
							<h3 align="center">Total Data : <span id="total_records" name="total_records"></span></h3>
							<table class="table table-striped table-bordered">
								<thead>
									<tr>
										<th> id </th>
										<th> nama </th>
										<th> departemen </th>
										<th> section </th>
										<th> sub section </th>
										<th> group </th>
										<th> sub group </th>
									</tr>
								</thead>
								<tbody>
									
								</tbody>
							</table>
						</div>
					</div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

route:

Route::get('/pages/evaluation', 'LivesearchController@indexing');
Route::get('/pages/evaluation/search', 'LivesearchController@search')->name('pages.evaluation.search');

Please or to participate in this conversation.