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

AbdulBazith's avatar

How to display values in returned from ajax call in tabular format Laravel?

Guys I have a data in table which I displayed in view.blade in tabular format This is the code

<thead>

 <th> <a href="" class="btn btn-success btn-sm" style="width: 100%;">Search</a></th>

</thead>

<thead >


              <th>Date</th>
              <th>Time</th>
              <th>Purchased Milk (Lt)</th>
              <th>Self Milk (Lt)</th>
              <th>Total Milk (Lt)</th>
              <th>Sold Milk (Lt)</th>
              <th>Excess Milk (Lt)</th>
              <th>Balance Milk (Lt)</th>


      </thead>

      <tbody>
            @foreach($overalls as $overall)
                <tr>

                    <td>{{ $overall->date }}</td>
                    <td>{{ $overall->time }}</td>
                    <td>{{ $overall->purchased_milk }}</td>
                    <td>{{ $overall->self_milk }}</td>
                    <td>{{ $overall->total_milk }}</td>
                    <td>{{ $overall->sold_milk }}</td>
                    <td>{{ $overall->excess_milk }}</td>
                    <td>{{ $overall->balance_milk }}</td>
</tr>

I have a search box to filter the displayed result. I wrote ajax call for the search box. That is if I enter a name in the search box the name is taken to the controller by ajax call and then searches the details of that name and then I displayed the search result in the controller itself as tabular format and returned the output.

this is my ajax



<script type="text/javascript">
    $('#search_balance').on('keyup',function(){
        $.ajax({
        type : 'get',
        url : '{{URL::to('search_overall_stock_details')}}',
        data:{             
                'search_balancem': $('#search_balance').val()
        },
        success:function(data){
         $('tbody').html(data);
        }
        });
        })
    </script>



This is my controller


public function search_overall_stock_details( Request $request )
    {
                    $output="";

                    $overallstock = Overallstock::where(function ($query) use ($request)
                       {

                       
                         if (!empty($request->search_balance)) {
                            $query->Where('date', 'LIKE', '%' . $request->search_balance . '%');
                          }

                    })->orderBy('created_at','desc')->paginate(5);
                     if($overallstock)
                    {
                    foreach ($overallstock as $key => $overallstocke)
                    {

                    $output.='<tr>'.

                    '<td>'.$overallstocke->date.'</td>'.

                    '<td>'.$overallstocke->time.'</td>'.

                    '<td>'.$overallstocke->purchased_milk.'</td>'.

                    '<td>'.$overallstocke->self_milk.'</td>'.

                    '<td>'.$overallstocke->total_milk.'</td>'.

                    '<td>'.$overallstocke->sold_milk.'</td>'.

                    '<td>'.$overallstocke->excess_milk.'</td>'.

                    '<td>'.$overallstocke->balance_milk.'</td>'.

                    '</tr>';

                    }
                    return Response($output);
                    }


But in some reasons its very difficult to work with tables in that controller.

What I need is to display the search result in tabular format in the same view.balde itself. i know need to write the tabular format in the controller.

Can anyone help me please ..!!

0 likes
13 replies
Sergiu17's avatar

If you need this with VueJs, we can help you, jQuery is quite hard for me))

1 like
AbdulBazith's avatar

@Sergiu17 @jlrdw thankz. i tried with you sugestions. i achieved part . but few mistakes please help

This is my controller


public function search_overall_stock_details( Request $request )
    {                  

                    $sels = Overallstock::where(function ($query) use ($request)
                       {

                       
                         if (!empty($request->search_balance)) {
                            $query->Where('date', 'LIKE', '%' . $request->search_balance . '%');
                          }

                    })->orderBy('created_at','desc')->paginate(5);
                   
                    return Response($sels);
       }



This is my ajax


<script type="text/javascript">
    $('#search_balance').on('keyup',function(){
        $.ajax({
        type : 'get',
        url : '{{URL::to('search_overall_stock_details')}}',
        data:{             
                'search_balancem': $('#search_balance').val()
        },
        success:function(sels){
         console.log(sels);
         $('tbody').html(sels);
        }
        });
        })
    </script>

I passed the search value through ajax to controller and returned it. The returned value is correct. It fetched the correct value and I displayed it in console. But after that how can I pass the ‘sels’ to the for loop. Display is the problem here. Kindly help me..

This is my view.blade


<tbody>
            @foreach($sels as $sel)
                <tr>
                 
                    <td>{{ $sel->self_stock_id }}</td>
                    <td>{{ $sel->date }}</td>
                    <td>{{ $sel->time }}</td>
                    <td>{{ $sel->no_of_litre }}</td>
                    <td>{{ $sel->note }}</td>
</tr>
</tbody>


Kindly help me.. need to pass the value to for loop

2 likes
Snapey's avatar

Whatever is in your blade file is a little irrelevant. You have chosen to go down the ajax route so you also need to know how to iterate over the results and create the DOM output required. Its got NOTHING to do with what you did in blade earlier.

You can find examples of this by searching for ajax jquery table

https://stackoverflow.com/questions/17724017/using-jquery-to-build-table-rows-from-ajax-response-json

Perhaps a plugin like this would help

http://www.jquery-bootgrid.com/examples#data

Or use a frontend library like Vue

1 like
AbdulBazith's avatar

@Snapey thank you. but my view.blade file is a big one. in my application iam having a menu view. if i click that it moves to the index controller

this is my controller


public function index()
    {
        $sels = Self_stock::orderBy('created_at','desc')->paginate(5);

        return view('Self_stock.view')->withsels($sels);
    }

But this view shows whole data. so i kept a search bar in this view file with ajax call so that i need to replace the returned values in the for loop. so it displays the new searched value.

This is what my objective. having a view file which displays the whole data using for loop. kept a search bar, when user types a keyword in the search bar then it goes to ajax with that keyword and moves to controller and searches the word and then returns to the ajax. after returning the for loop which displays the whole data must display only the searched value..

simply saying a achieved this in controller

this is the controller file


public function search_overall_stock_details( Request $request )
    {
                    $output="";

                    $overallstock = Overallstock::where(function ($query) use ($request)
                       {

                       
                         if (!empty($request->search_balance)) {
                            $query->Where('date', 'LIKE', '%' . $request->search_balance . '%');
                          }

                    })->orderBy('created_at','desc')->paginate(5);
                     if($overallstock)
                    {
                    foreach ($overallstock as $key => $overallstocke)
                    {

                    $output.='<tr>'.

                    '<td>'.$overallstocke->date.'</td>'.

                    '<td>'.$overallstocke->time.'</td>'.

                    '<td>'.$overallstocke->purchased_milk.'</td>'.

                    '<td>'.$overallstocke->self_milk.'</td>'.

                    '<td>'.$overallstocke->total_milk.'</td>'.

                    '<td>'.$overallstocke->sold_milk.'</td>'.

                    '<td>'.$overallstocke->excess_milk.'</td>'.

                    '<td>'.$overallstocke->balance_milk.'</td>'.

                    '</tr>';

                    }
                    return Response($output);
                    }


but the codes are in controller i need this to be in view file that it..

Please do reply for this kindly

1 like
Snapey's avatar

So what does not work?

Have you used the network tools in the browser to check the ajax response?

1 like
AbdulBazith's avatar

@Snapey while the tabular format in controller it worked. but when i trying it in view file something iam missing...

yaa i checked it using console.log(sels). it displays the correct searched value in console. the values are correcting passing in controller and returning. after the ajax return what should i do to display it in the same tabular form.

1 like
Snapey's avatar

It should be as you have done, insert the formatted data into the table body.

1 like
Snapey's avatar

basically, as you are doing. http://api.jquery.com/html/

You should really give your table an ID so that it is not confused if there is more than one table on the page

You say that selscontains the formatted string, but check. This needs to be just the raw html that you want to insert in table body. It is no use if it is wrapped in a json object. In which case, you need to pull out the raw html string.

What do you see as a result of console.log(sels)

1 like
Tray2's avatar

In vanilla Javascript I would do something like this.

var xhttp = new XMLHttpRequest();
var myTable = document.querySelector('#my-table');
var tableRows = '';

xhttp.ontimeout = function() {
    //Do dome gracefull error handling
}

xhttp.onreadystatechange = function() {
    if (xhttp.readyState === 4) {
        var response = JSON.parse(xhttp.response);
        for (i = 0; i < response.length; i++) {
          tableRows += '<tr><td>' + response[i].key1 + '</td><td>' + response[i].key2 + '</td></tr>';
        }             
        
        myTable.innerHTML = tableRows;
    }
}; 

xhttp.open('GET', 'http://myEndpoint', true);
xhttp.timeout = 10000;
xhttp.send();
1 like
AbdulBazith's avatar

@Snapey sorry sterday office leave so cant reply..

in the console.log(sels) i got the output the filtered data. but now how can i make the output display in tabular format.

to be simple just have view file that displays all the records of a single table in tabular format. having a search box. if client types a name and search say for example "Abdul" this is keyword typed in the search box then the name is taken to controller using ajax onchange event of search box and in controller it is searched and the the records of name abdul is taken and returned to ajax, not the out put must be displayed in the same tabular format. simply saying like live search.

what i achieved is everything is done. and the searched is returned in ajax. but after that how could i display it in tabular format in the same view file.

i finished this by doing it in controller. after search is done i displayed it in tabular format in controller itself and then returned the out put. but its not convenient to write those in controller.

this is my controller



public function search_overall_stock_details( Request $request )
    {
                    $output="";

                    $overallstock = Overallstock::where(function ($query) use ($request)
                       {

                       
                         if (!empty($request->search_balance)) {
                            $query->Where('date', 'LIKE', '%' . $request->search_balance . '%');
                          }

                    })->orderBy('created_at','desc')->paginate(5);
                     if($overallstock)
                    {
                    foreach ($overallstock as $key => $overallstocke)
                    {

                    $output.='<tr>'.

                    '<td>'.$overallstocke->date.'</td>'.

                    '<td>'.$overallstocke->time.'</td>'.

                    '<td>'.$overallstocke->purchased_milk.'</td>'.

                    '<td>'.$overallstocke->self_milk.'</td>'.

                    '<td>'.$overallstocke->total_milk.'</td>'.

                    '<td>'.$overallstocke->sold_milk.'</td>'.

                    '<td>'.$overallstocke->excess_milk.'</td>'.

                    '<td>'.$overallstocke->balance_milk.'</td>'.

                    '</tr>';

                    }
                    return Response($output);
                    }

What i done in the controller i need to do in the view file thats it.

I am suffering with this for past 5 days. kindly help me please. is this clear or else need to explain it further detailly ...

1 like
AbdulBazith's avatar
AbdulBazith
OP
Best Answer
Level 5

The solution is

to write it in ajax

this is the right code


$('#search_frmdate,#search_date,#search_time,#search_nl,#search_note').on('keyup',function(){
        $.ajax({
        dataType: 'json',
        type : 'get',
        url : '{{URL::to('search_excess_milk_details')}}',

        data:{ 'search_frmdate': $('#search_frmdate').val(),
                'search_todate': $('#search_date').val(),
                'search_time': $('#search_time').val(),
                'search_nl': $('#search_nl').val(),
                'search_note': $('#search_note').val()
        },
        success:function(data)
        {
            console.log(data);
            var res='';
            $.each (data, function (key, value) {
            res +=
            '<tr>'+
                '<td>'+value.date+'</td>'+
                '<td>'+value.time+'</td>'+
                '<td>'+value.no_of_litre+'</td>'+
                '<td>'+value.note+'</td>'+
           '</tr>';

   });

            $('tbody').html(res);
        }


    });
    })

and the search in controller is


public function search_excess_milk_details( Request $request )
    {               
                    $xcess_milks = Excess_milk::where(function ($query) use ($request)
                       {                 

                            if (!empty($request->search_time)) {
                            $query->Where('time', 'LIKE', '%' . $request->search_time . '%');
                         }
                    })->orderBy('date','asc')->get;

   return Response($xcess_milks);
}

2 likes

Please or to participate in this conversation.