-1

I have JSOn data coming from my Function, i do not need all the data and had to create some data too based upon the data i am getting, There are many code outlying which specify how can i loop over json data and display it

$.ajax({url: 'page.php',
        data: {id: 1},
        dataType: 'json',
        type:'POST',
        success: function (json) {
            div.html('<table align="left" width="70%" class="table table-striped borderless p-l-xl">'+
                    '<tr>'+
                        '<td>d1</td><td>d2</td><td>Action</td></tr>'+
                        '<tr><td>'+json.d1+'</td><td>'+json.d2+'</td>'+
                        '<td><a href="javascript:;" class="t" data-id="'+ json.id +'" data-sid="'+json.sid+'">Delete</a></td>'+
                    '</tr>'+
                '</table>').removeClass('loading');
            } 
    });

Tried using this code

How to iterate JSON object with jQuery

but i am confused how i feed my own href with custom data and separate headers

Did a Small Update

$.each(json,function(index,item){
                $('<table><tr>').append(
                    $("<td>").text(item.d1),
                    $("<td>").text(item.d2),
                    $("<td>").html('<a href="javascript:;" class="d" data-sid="'+ json.id+'" data-id="'+json.id+'">Delete</a></td>')
                ).appendTo(div);
        });

now it works and create a seperate for each record, amd missing headers

while i want that all the rows should be under one TABLE Tag and have headers

John
  • 15
  • 4
  • Your question is a bit unclear, what are you trying to accomplish exactly? Could you also post your entire Ajax call? – Adam Feb 01 '19 at 20:09
  • 4
    you haven't explained precisely what the problem is. What does your data structure look like? Please give us an example. And what do you want the final output of your HTML to look like? And what is happening to your code now? Do you get errors, or unwanted output? We can't help you yet because we don't know what it is you are trying to achieve, and we don't really know precisely what problem you're having. – ADyson Feb 01 '19 at 20:10
  • Data is as JSON call – John Feb 01 '19 at 20:12
  • JSON stands for Javascript Object notation. It is a specification that allows you to represent javascript objects as strings. `jQuery.ajax` automatically parses the resulting json. The `success` method is passed actual javascript. There is no such thing as a "JSON Object" and you are not working with JSON, you are working with a javascript object literal. – Marie Feb 01 '19 at 20:16
  • i know that what i am saying is my result is coming as JSON, so rather than fixing that why we are deciding what is JSOn or What NOT – John Feb 01 '19 at 20:18
  • Your result is not "coming as JSON." – Marie Feb 01 '19 at 20:19
  • 1
    @Marie `jQuery.ajax` *can* auto parse for the client. But it's not a guarentee. You have to make sure the response or request is setup correctly for it to do so – Taplar Feb 01 '19 at 20:19
  • 1
    If the response is valid JSON and the request specifies the `json` (which we can see it does) datatype it is guaranteed. – Marie Feb 01 '19 at 20:19
  • 1
    I'm simply pointing out your first statement was a blanket absolute, which was incomplete, as you just affirmed. – Taplar Feb 01 '19 at 20:20
  • 1
    @John your code is set up (due to the `dataType: "json"` ajax option) to expect JSON coming from the server, and then automatically convert it to a JS variable (either an object or array, depending on what JSON is received). So `data` should be a variable, assuming that the received JSON is valid (you'll get a console error if not). But you still haven't explained to us what issue you are facing after that, specifically. We can't advise you because we don't know the detail of your problem, and we don't know what you are wanting your code to achieve. – ADyson Feb 01 '19 at 20:21
  • do we have a solution or not – John Feb 01 '19 at 20:23
  • 2
    no, we can't give you a solution because you haven't explained the problem clearly enough. All you've told us is you're confused about something...but I'll say it again one more time: we don't know a) what you want to achieve and b) what is going wrong currently – ADyson Feb 01 '19 at 20:24
  • Did a Small Update, Check my Main POst – John Feb 01 '19 at 20:39

2 Answers2

1

Following your update, it's a little clearer.

You say

"while i want that all the rows should be under one TABLE Tag and have headers"

...so the simple solution to that is to create the table first before you start the loop, and add the headers at that time as well. Then each time in the loop, just append a new row to the existing table, instead of creating a whole new table.

This logic isn't too complicated once you think about it like that

Here is a demo which illustrates what I mean, using some dummy data instead of the response from the AJAX.

//dummy test data
var json = [{
    "id": 1,
    "d1": "Text 1",
    "d2": "Text 2"
  },
  {
    "id": 2,
    "d1": "Text A",
    "d2": "Text B"
  },
  {
    "id": 3,
    "d1": "Text X",
    "d2": "Text Y"
  },
];

var div = $("#div1");

var table = $('<table id="table1"><tr><th>Heading 1</th><th>Heading 2</th><th>Heading 3</th></tr>');

$.each(json, function(index, item) {
  var row = $("<tr>");
  row.append(
    $("<td>").text(item.d1),
    $("<td>").text(item.d2),
    $("<td>").html('<a href="javascript:;" class="d" data-sid="' + json.id + '" data-id="' + json.id + '">Delete</a></td>')
  );
  row.appendTo(table);
});

table.appendTo(div);
table {
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #cccccc;
  padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1"></div>
ADyson
  • 57,178
  • 14
  • 51
  • 63
1

I believe this is what you are trying to achieve. (without jQuery other than the $.get()).

  1. Given some data (here are fake blog posts)
  2. Modify the data is some way
  3. Place the modified data into a table
  4. Provide an "Action" column with a link to delete the row

$.get('https://jsonplaceholder.typicode.com/posts', transformData);

function transformData(posts) {
  let tableData = posts.map(post => {
    return {
      id: post.id,
      title: post.title,
      added: 'added'
    }
  });
  makeTable(tableData);
}

function deleterow(el) {
  alert('Deleting row with id: ' + el.dataset.id);
}

function makeTable(data) {
  var table = document.createElement("table");
  table.style.border = "1px";
  var headerRow = document.createElement("thead");
  headerRow.style.backgroundColor = "#ccc";

  Object.keys(data[0]).forEach(key => {
    let headerCol = document.createElement("td");
    headerCol.textContent = key;
    headerRow.appendChild(headerCol);
  });
  let actionCol = document.createElement('td');
  actionCol.textContent = 'Action';
  headerRow.appendChild(actionCol);
  table.appendChild(headerRow);

  data.forEach(item => {
    let row = document.createElement("tr");
    Object.keys(item).forEach(key => {
      let col = document.createElement("td");
      col.textContent = item[key];
      row.appendChild(col);
    });
    let action = document.createElement("a");
    action.href = 'javascript:void(0);';
    action.textContent = 'Delete';
    action.setAttribute("onclick", 'deleterow(this)');
    action.dataset.id = item.id;
    action.dataset.title = item.title;
    action.dataset.added = item.added;
    row.appendChild(action);
    table.appendChild(row);
  });
  document.body.appendChild(table);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
  • it's also unclear how any of the stuff above about "posts" relates to the OP's data or desired HTML output. What does your code output? OP's data doesn't have "title" or "added" properties, as far as we know. – ADyson Feb 01 '19 at 21:00
  • A data, then transformed data, into a table, with headers, and an action column with a link. Done programmatically - the part the OP could not figure out. – Randy Casburn Feb 01 '19 at 21:01
  • ok but you could at least make it match the data structure in the question – ADyson Feb 01 '19 at 21:01
  • But that's why your answer doesn't run...by using contrived data structures we cannot actually "show" them an output. I use jsonplaceholder all the time on here and people generally appreciate that they can visualize the result. I can look at your answer and "see" what it does...but can the OP? – Randy Casburn Feb 01 '19 at 21:03
  • I would agree, except that your snippet doesn't run either...I just get a blank space (using the latest Chrome). But equally you could use a site like myjson.com to host any JSON structure you like, to imitate the structure in the question. Or just use static data for the purpose of the demo - the ajax isn't the important part.. – ADyson Feb 01 '19 at 21:04
  • Works fine for me. Are you use IE? – Randy Casburn Feb 01 '19 at 21:05
  • Let's' let the OP determine the value of this answer. Thanks. – Randy Casburn Feb 01 '19 at 21:05
  • No I'm using the latest version of Chrome – ADyson Feb 01 '19 at 21:05
  • Don't know what to tell you...just ran it Chrome with no problem. – Randy Casburn Feb 01 '19 at 21:06
  • console says "Failed to load resource: net::ERR_SSL_VERSION_INTERFERENCE" – ADyson Feb 01 '19 at 21:07
  • As I said, I understand your criticism, BUT, let's allow the OP to determine the value of this answer as it relates to the OPs needs - not your opinion. Thanks, – Randy Casburn Feb 01 '19 at 21:08
  • That's fine. I was only pointing it out as I felt maybe the answer could be improved. Not trying to do anyone down....nothing personal. – ADyson Feb 01 '19 at 21:09
  • It seems to have loaded at long last, have an upvote. I modified mine to be runnable too. – ADyson Feb 01 '19 at 21:14