How to show no result found in Ajax Laravel search?

229 Views Asked by At

I want to show 'No Results Found' in the Laravel Ajax search. In my case, if there is no record, it shows a blank screen. So I want to change it to "No results found." Can someone help me?

View

<div class="row" style="text-align: center;padding-top: 25px;">
     <div class="col-md-8" >
          <h2 id="dynamic-row"></h2>
     </div>
</div>    
<script>
    $('body').on('click' ,'#search' , function(){
        var from = $('#from').val();
        var to = $('#to').val();
        $.ajax({
            method: 'POST',
            url: '{{ route("fare.search") }}',
            dataType: 'json',
            data: {
                '_token' : '{{ csrf_token() }}',
                from : from,
                to: to,
            },
            success: function(res){
                var tableRow = '';
                $('#dynamic-row').html('');
                $.each(res , function(index,value){
                    tableRow = '<h2>RS &nbsp;'+value.fare+'/-</h2>';                   
                    $('#dynamic-row').append(tableRow);
                    //$('#dynamic-row').css('font-weight', 'bold');
                    
                })
            }
        })
    })
</script>
1

There are 1 best solutions below

2
On

Just simply return the 404 on "No result found" in Controller.

return response()->json('No Result Found', 404);   

And add the error function in ajax call:

$('body').on('click' ,'#search' , function(){
        var from = $('#from').val();
        var to = $('#to').val();
        $.ajax({
            method: 'POST',
            url: '{{ route("fare.search") }}',
            dataType: 'json',
            data: {
                '_token' : '{{ csrf_token() }}',
                from : from,
                to: to,
            },
            success: function(res){
                var tableRow = '';
                $('#dynamic-row').html('');
                $.each(res , function(index,value){
                    tableRow = '<h2>RS &nbsp;'+value.fare+'/-</h2>';                   
                    $('#dynamic-row').append(tableRow);
                    //$('#dynamic-row').css('font-weight', 'bold');
                    
                })
            },
            error: function(res){
              console.log(res);
            }
        })
    })