0

I am getting this JSON response from to back-end.

{
  "data": [
    {
      "id": 6,
      "firstname": "fname",
      "middlename": "mname",
      "lastname": "lname",
    },
    ...
  ]
}

Creating table from the JSON response using jquery datatable using ajax request.

$number = 1;
$("#people-table").DataTable({
    ajax: {
        url: window.location.href + '/fetchdata',
        method: "GET",
        dataType: "json",
        dataSrc: "data"
    },
    columns: [
        {
            render: function () {
                return $number++;
            }
        },
        { data: 'firstname' },
        { data: 'middlename' },
        { data: 'lastname' },
    ]
});
<table>
  <thead>
     <tr>
        <th>No.</th>
        <th>Profile</th>
        <th>Firstname</th>
        <th>Middlename</th>
        <th>Lastname</th>
    </tr>
  </thead>
  <tbody>
      {{-- data --}}
  </tbody>
</table>

I am getting proper output for this code in the html table, but now I want to combine all three field firstname, middlename, and lastname into one field called fullname using jquery datatable

1 Answer 1

1

You can do something like this instead of DataTables. This is a pure javascript example.

HTML

 <thead>
  <tr>
     <th>No.</th>
     <th>Profile</th>
     <th>Full Name</th>
 </tr>
</thead>
<tbody id="myDataTable"></tbody>

Javascript

       <script>

       function MyFunction(){
        $.ajax({
         url: 'your-url' ,
         type: 'get',
         datetype:"json",
         success: function(res){
            var myData = res.data //collection from backend
            let str = "";
            myData.forEach((data, key) => {
                str += `
                    <tr>
                        <td> ${data.no} </td>
                        <td> ${data.profile} </td>
                        <td> 
                           ${data.firstname} 
                           ${data.middlename}
                           ${data.lastname} 
                        </td>
            
                    </tr>
                 `
            })
            $("#myDataTable").html(str);
         }
        })
       }
      
    </script>

Make sure to call your function whenever you need it to display.

Sign up to request clarification or add additional context in comments.

2 Comments

This is fine for this example because I am getting all the data at once but what if I use server-side processing at that time this is not going to work.
if server side processing then you can modify your collection and concatenate firstname, middlename and lastname. You can achieve this by using map stackoverflow.com/questions/43711940/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.