0

Hi I am submitting a html form using ajax and I am receiving a JSON Array response in return. So can you please suggest me how can I append this response in html table dynamically.

this is my form :

 <form id="myForm" method="POST">
   <input type="submit" value="Refresh">
 </form>

Python Django Backed Code:

def refresh(request):
    user = usertab.objects.all().values()
    d={"data" : list(user)}
    return JsonResponse(d)

And here I am calling my BE code using Ajax :

 $(document).on('submit','#myForm',function(e){
        e.preventDefault();
        $.ajax({
            type:'POST',
            url: '/refresh/',
            data:{
                csrfmiddlewaretoken : "{{ csrf_token }}"
            },
            success: function(d){
                for (a in d['data']){
                  //How to append data in html table
                }

            },
            error: function(xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    });

This is my html table :

<table id="myTable">
    <thead>
        <tr>
            <th>id</th>
            <th>username</th>
            <th>email</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td> ??????? </td>
            <td> ??????? </td>
        </tr>
    </tbody>

</table>
2

1 Answer 1

0

See demo of dynamic table rows generation.
Note that the code is not using any external js library.

<html>
<head>

<script>

var data = [{id:12,user:'jack',email:'[email protected]'},
        {id:14,user:'dan',email:'[email protected]'}]

		
function populate_table() {
   let table = document.getElementById('demo_table');
   for(var i = 0; i < data.length; i++) {
        let row = table.insertRow(-1);
		let cell = row.insertCell(0);
		let text = document.createTextNode(data[i].email);
        cell.appendChild(text);
		cell = row.insertCell(0);
		text = document.createTextNode(data[i].user);
        cell.appendChild(text);
		cell = row.insertCell(0)
		text = document.createTextNode(data[i].id);
        cell.appendChild(text);
   }
}

</script>
</head>
<button onclick="populate_table()">Populate table</button>

<table id="demo_table">
    <thead>
        <tr>
            <th>id</th>
            <th>username</th>
            <th>email</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

</html>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.