Sachin Sanchaniya
Sachin Sanchaniya

Reputation: 1044

Display Data In Table Using AJAX JSON PHP In Correct Way

I am making an admin panel. So I want to display data from database in table when page is load. I am Confused that, I display whole table from backend side in div or put data only ??

For Example :

success:function(response){
    $("#result").html(result);
}

That Will Display Whole Table In result div. That will Come From Backend side.

OR

 success:function(response){
        $("#result").html('<table><tr><td>'+response.name+'</td><td>'+response.password+'</td></tr>');
    }

If This is The Way for printing data in table then It will Print Only the row at once. Not full data in each .

Please Help me to solve this problem.

Upvotes: 0

Views: 1988

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

It would be obviously better to get the data from the backend as a JSON output and use the JSON from the response to construct the table in the client side. The main reasons being:

  1. Lesser code footprint between the client and server.
  2. Ability to change the view, if JSON, it is not tied with HTML.

In future, if you want to change the structure or if you need to use the same output in a different page, in a different way, you don't need to change the underlying PHP, instead, you can just change the rendering mechanism.

Have the server sent out a JSON output like this:

[{
  "name": "Praveen",
  "age": 27
}, {
  "name": "Kumar",
  "age": 25
}]

And make the JavaScript do the rest.

var jsonResponse = [{
  "name": "Praveen",
  "age": 27
}, {
  "name": "Kumar",
  "age": 25
}];
$('body').append(function () {
  var table = $('<table />');
  var headr = $('<tr />');
  headr.append('<th>Name</th>');
  headr.append('<th>Age</th>');
  headr.appendTo(table);
  $.each(jsonResponse, function (i, v) {
    var tr = $('<tr />');
    tr.append('<td>' + v.name + '</td>');
    tr.append('<td>' + v.age + '</td>');
    tr.appendTo(table);
  });
  return table;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 3

Muhammed Imran Hussain
Muhammed Imran Hussain

Reputation: 2125

Your both options correct but I found it is good practice separating logic and views, means it is good to generate html view in front-end.

Now, to generate table view with multiple rows, your response data should be properly structured for example json object array.

If you got my explanation then you can follow this post: Loop through a JSON array to create a Table

Let me know for any queries

Upvotes: 0

Related Questions