Home > Back-end >  How do I populate HTML tables with an ajax response?
How do I populate HTML tables with an ajax response?

Time:11-17

I have a laravel blade view/page that I'd like to update without refreshing the page.

The blade.php code is working fine and retrieving data from a MySQL database - but the ajax/javascript isn't.

Apparently my AJAX calls are not even returning JSON but an object.

I come from a background of C# and never touched ajax/javascript/php in my life and I'd appreciate it if anyone could help me.

The controller.php works and returns the data I need which LOOKS like json but apparently isn't json.

What I would like to do is refresh the page a user is on (without reloading it), grab the data from a MySQL database and update the pre-existing tables with this new data - if there is any new data.

view.blade.php:

<table  id="mainTable">
  <thead>
    <tr>
        <th>@lang('ID')</th>
        <th>@lang('Name')</th>
        <th>@lang('Date')</th>
        <th>@lang('Details')</th>
    </tr>
  </thead>
  <tbody>
    @forelse($items as $data)
        <tr>
            <td data-label="@lang('ID')">
                {{ $loop->index   1 }}
            </td>
            <td data-label="@lang('Name')">{{ $data->name }}</td>
            <td data-label="@lang('Date')">{{ $data->created_at }}</td>
            <td id="detailz" data-label="@lang('Details')">{{ $data->details }}</td>
        </tr>
    @empty
        <tr>
            <td colspan="100%" >@lang('No data.')</td>
        </tr>
    @endforelse
  </tbody>
</table>

AJAX: (Not working)

function updatePost() {
setInterval(function() {
    $.ajax({
        type: "GET",
        url: "{{route('user.posts.update')}}", // Route works.
        success: function( response ){

            $('#mainTable')[0].reset();
             $("tbody").html("");
             $.each(response, function( index, value ) {
                var row = $("<tr><td>"
                              value.name   "</td><td>"
                              value.details   "</td><td>"
                              value.created_at   "</td><td>");

                $("tbody").append(row);
            });

        },
        error: function( response ){
            console.log("Error!");
            console.log(response);
        }
    });
}, 5000); // every 5s

controller.php:

  public function postUpdate(){
      $pageTitle = 'Post Update';
      $data = DataHistory::where('user_id', Auth::user()->id)->latest()->paginate(getPaginate());
      return response()->json($data);
    }

I've tried many different methods in ajax but apparently I can't seem to access the inner elements of the data.

Here's a sample of the data:

{
    "current_page":1,
    "data":[
        {
            "id":34,
            "user_id":1,
            "name":"RANDOM NAME DATA",
            "details":"RANDOM DETAILS",
            "created_at":"2022-11-16T15:02:56.000000Z"
        },{
            "id":32,
            "user_id":1,
            "name":"RANDOM NAME DATA 2",
            "details":"RANDOM DETAILS 2",
            "created_at":"2022-11-16T10:19:29.000000Z"
        },
    "first_page_url":"https:\/\/xyz.com/posts/update/?page=1",
    "from":1,
    "last_page":1,
    "last_page_url":"https:\/\/xyz.com/posts/update/?page=1",
    "links":[
        {
            "url":null,
            "label":"&laquo; Previous",
            "active":false
        },{
            "url":"https:\/\/xyz.com/posts/update/?page=1",
            "label":"1",
            "active":true
        },{
            "url":null,
            "label":"Next &raquo;",
            "active":false
        }
    ],
    "next_page_url":null,
    "path":"https:\/\/xyz.com/posts/update/",
    "per_page":20,
    "prev_page_url":null,
    "to":7,
    "total":7
}

How will I be able to achieve this? Am I going in the right direction?

CodePudding user response:

What you have there is valid JSON, but its an object not an array. There's an array within it, in the data property. So if you loop through response.data it will work:

$.each(response.data, function( index, value ) {

CodePudding user response:

You would want to iterate the response property data

         $.each(response.data, function( index, value ) {

so that value.name will actually contain the values from these objects from your demo data:

    {
        "id":34,
        "user_id":1,
        "name":"RANDOM NAME DATA",
        "details":"RANDOM DETAILS",
        "created_at":"2022-11-16T15:02:56.000000Z"
    },{
        "id":32,
        "user_id":1,
        "name":"RANDOM NAME DATA 2",
        "details":"RANDOM DETAILS 2",
        "created_at":"2022-11-16T10:19:29.000000Z"
    },
  • Related