Get data from Django model and display in a html table using AJAX
up vote
1
down vote
favorite
I've searched and implemented so many different ways to display a html table, using AJAX, from a JsonResponse (Django) - but to no avail.
Currently, the furthest I've gotten is a response to the network console:
{"products": "[{"model": "products.product", "pk": 2, "fields": {"name": "Bag", "description": "Carries items conspicuously ", "price": "10.99"}}, {"model": "products.product", "pk": 3, "fields": {"name": "iPhone 8 Plus", "description": "a mobile device from Apple", "price": "850.00"}}, {"model": "products.product", "pk": 8, "fields": {"name": "Shoes", "description": "For your feet", "price": "49.50"}}, {"model": "products.product", "pk": 9, "fields": {"name": "Gloves", "description": "For your hands", "price": "2.99"}}, {"model": "products.product", "pk": 10, "fields": {"name": "Blanket", "description": "Keep warm", "price": "13.79"}}, {"model": "products.product", "pk": 11, "fields": {"name": "Gown", "description": "Sleep time", "price": "25.99"}}]"}
but I want this dictionary to display on my html table via ajax
My django model looks like this:
class Product(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length = 200)
description = models.TextField()
price = models.DecimalField(decimal_places=2,max_digits=100000)
my django view:
def product_list(request):
productData = serializers.serialize("json", Product.objects.all())
return JsonResponse({"products": productData})
my html page body:
<body style='text-align:center'>
<table class="table table-striped" id="product-table">
<thead class="thead-dark"><th>Item<th>Description<th>Price</th><th></th></thead>
<tr>
<form id="add-product">{% csrf_token %}
<td><a><input type="text" class="form-control form-control-sm" id="newProductName" placeholder="Product name"></a></td>
<td><a><input type="text" class="form-control form-control-sm" id="newProductDesc" placeholder="Product description"></a></td>
<td><a><input type="text" class="form-control form-control-sm" id="newProductPrice" placeholder="£--.--"></a></td>
<td><button type="submit" class="btn btn-primary btn-sm" id="newProductSubmit">add</button></td>
</form>
</tr>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="{% static 'main.js' %}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
and my ajax function to get the jsonresponse:
$(document).ready(function() {
$.ajax({
url: 'products/getProducts/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
jData = JSON.parse(data)
alert("got json products!");
}
});
});
with the ajax, I am aware I'm missing something to convert the data to html and append to my table, but when I tried this it simply didn't add anything
json ajax django
add a comment |
up vote
1
down vote
favorite
I've searched and implemented so many different ways to display a html table, using AJAX, from a JsonResponse (Django) - but to no avail.
Currently, the furthest I've gotten is a response to the network console:
{"products": "[{"model": "products.product", "pk": 2, "fields": {"name": "Bag", "description": "Carries items conspicuously ", "price": "10.99"}}, {"model": "products.product", "pk": 3, "fields": {"name": "iPhone 8 Plus", "description": "a mobile device from Apple", "price": "850.00"}}, {"model": "products.product", "pk": 8, "fields": {"name": "Shoes", "description": "For your feet", "price": "49.50"}}, {"model": "products.product", "pk": 9, "fields": {"name": "Gloves", "description": "For your hands", "price": "2.99"}}, {"model": "products.product", "pk": 10, "fields": {"name": "Blanket", "description": "Keep warm", "price": "13.79"}}, {"model": "products.product", "pk": 11, "fields": {"name": "Gown", "description": "Sleep time", "price": "25.99"}}]"}
but I want this dictionary to display on my html table via ajax
My django model looks like this:
class Product(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length = 200)
description = models.TextField()
price = models.DecimalField(decimal_places=2,max_digits=100000)
my django view:
def product_list(request):
productData = serializers.serialize("json", Product.objects.all())
return JsonResponse({"products": productData})
my html page body:
<body style='text-align:center'>
<table class="table table-striped" id="product-table">
<thead class="thead-dark"><th>Item<th>Description<th>Price</th><th></th></thead>
<tr>
<form id="add-product">{% csrf_token %}
<td><a><input type="text" class="form-control form-control-sm" id="newProductName" placeholder="Product name"></a></td>
<td><a><input type="text" class="form-control form-control-sm" id="newProductDesc" placeholder="Product description"></a></td>
<td><a><input type="text" class="form-control form-control-sm" id="newProductPrice" placeholder="£--.--"></a></td>
<td><button type="submit" class="btn btn-primary btn-sm" id="newProductSubmit">add</button></td>
</form>
</tr>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="{% static 'main.js' %}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
and my ajax function to get the jsonresponse:
$(document).ready(function() {
$.ajax({
url: 'products/getProducts/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
jData = JSON.parse(data)
alert("got json products!");
}
});
});
with the ajax, I am aware I'm missing something to convert the data to html and append to my table, but when I tried this it simply didn't add anything
json ajax django
Not fully clear that you want to display the response data in the Form input fields or in a table?
– Zollie
Nov 11 at 14:28
@zollie in a table, the form is a separate part
– Yash Morar
Nov 11 at 14:32
OK, I am checking it and get back to you.
– Zollie
Nov 11 at 15:10
1
You have double-encoded your data. You shouldn't put the JSON result from serialize into another dict which itself is serialized by JsonResponse.
– Daniel Roseman
Nov 11 at 15:53
add a comment |
up vote
1
down vote
favorite
up vote
1
down vote
favorite
I've searched and implemented so many different ways to display a html table, using AJAX, from a JsonResponse (Django) - but to no avail.
Currently, the furthest I've gotten is a response to the network console:
{"products": "[{"model": "products.product", "pk": 2, "fields": {"name": "Bag", "description": "Carries items conspicuously ", "price": "10.99"}}, {"model": "products.product", "pk": 3, "fields": {"name": "iPhone 8 Plus", "description": "a mobile device from Apple", "price": "850.00"}}, {"model": "products.product", "pk": 8, "fields": {"name": "Shoes", "description": "For your feet", "price": "49.50"}}, {"model": "products.product", "pk": 9, "fields": {"name": "Gloves", "description": "For your hands", "price": "2.99"}}, {"model": "products.product", "pk": 10, "fields": {"name": "Blanket", "description": "Keep warm", "price": "13.79"}}, {"model": "products.product", "pk": 11, "fields": {"name": "Gown", "description": "Sleep time", "price": "25.99"}}]"}
but I want this dictionary to display on my html table via ajax
My django model looks like this:
class Product(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length = 200)
description = models.TextField()
price = models.DecimalField(decimal_places=2,max_digits=100000)
my django view:
def product_list(request):
productData = serializers.serialize("json", Product.objects.all())
return JsonResponse({"products": productData})
my html page body:
<body style='text-align:center'>
<table class="table table-striped" id="product-table">
<thead class="thead-dark"><th>Item<th>Description<th>Price</th><th></th></thead>
<tr>
<form id="add-product">{% csrf_token %}
<td><a><input type="text" class="form-control form-control-sm" id="newProductName" placeholder="Product name"></a></td>
<td><a><input type="text" class="form-control form-control-sm" id="newProductDesc" placeholder="Product description"></a></td>
<td><a><input type="text" class="form-control form-control-sm" id="newProductPrice" placeholder="£--.--"></a></td>
<td><button type="submit" class="btn btn-primary btn-sm" id="newProductSubmit">add</button></td>
</form>
</tr>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="{% static 'main.js' %}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
and my ajax function to get the jsonresponse:
$(document).ready(function() {
$.ajax({
url: 'products/getProducts/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
jData = JSON.parse(data)
alert("got json products!");
}
});
});
with the ajax, I am aware I'm missing something to convert the data to html and append to my table, but when I tried this it simply didn't add anything
json ajax django
I've searched and implemented so many different ways to display a html table, using AJAX, from a JsonResponse (Django) - but to no avail.
Currently, the furthest I've gotten is a response to the network console:
{"products": "[{"model": "products.product", "pk": 2, "fields": {"name": "Bag", "description": "Carries items conspicuously ", "price": "10.99"}}, {"model": "products.product", "pk": 3, "fields": {"name": "iPhone 8 Plus", "description": "a mobile device from Apple", "price": "850.00"}}, {"model": "products.product", "pk": 8, "fields": {"name": "Shoes", "description": "For your feet", "price": "49.50"}}, {"model": "products.product", "pk": 9, "fields": {"name": "Gloves", "description": "For your hands", "price": "2.99"}}, {"model": "products.product", "pk": 10, "fields": {"name": "Blanket", "description": "Keep warm", "price": "13.79"}}, {"model": "products.product", "pk": 11, "fields": {"name": "Gown", "description": "Sleep time", "price": "25.99"}}]"}
but I want this dictionary to display on my html table via ajax
My django model looks like this:
class Product(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length = 200)
description = models.TextField()
price = models.DecimalField(decimal_places=2,max_digits=100000)
my django view:
def product_list(request):
productData = serializers.serialize("json", Product.objects.all())
return JsonResponse({"products": productData})
my html page body:
<body style='text-align:center'>
<table class="table table-striped" id="product-table">
<thead class="thead-dark"><th>Item<th>Description<th>Price</th><th></th></thead>
<tr>
<form id="add-product">{% csrf_token %}
<td><a><input type="text" class="form-control form-control-sm" id="newProductName" placeholder="Product name"></a></td>
<td><a><input type="text" class="form-control form-control-sm" id="newProductDesc" placeholder="Product description"></a></td>
<td><a><input type="text" class="form-control form-control-sm" id="newProductPrice" placeholder="£--.--"></a></td>
<td><button type="submit" class="btn btn-primary btn-sm" id="newProductSubmit">add</button></td>
</form>
</tr>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="{% static 'main.js' %}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
and my ajax function to get the jsonresponse:
$(document).ready(function() {
$.ajax({
url: 'products/getProducts/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
jData = JSON.parse(data)
alert("got json products!");
}
});
});
with the ajax, I am aware I'm missing something to convert the data to html and append to my table, but when I tried this it simply didn't add anything
json ajax django
json ajax django
asked Nov 11 at 13:45
Yash Morar
448
448
Not fully clear that you want to display the response data in the Form input fields or in a table?
– Zollie
Nov 11 at 14:28
@zollie in a table, the form is a separate part
– Yash Morar
Nov 11 at 14:32
OK, I am checking it and get back to you.
– Zollie
Nov 11 at 15:10
1
You have double-encoded your data. You shouldn't put the JSON result from serialize into another dict which itself is serialized by JsonResponse.
– Daniel Roseman
Nov 11 at 15:53
add a comment |
Not fully clear that you want to display the response data in the Form input fields or in a table?
– Zollie
Nov 11 at 14:28
@zollie in a table, the form is a separate part
– Yash Morar
Nov 11 at 14:32
OK, I am checking it and get back to you.
– Zollie
Nov 11 at 15:10
1
You have double-encoded your data. You shouldn't put the JSON result from serialize into another dict which itself is serialized by JsonResponse.
– Daniel Roseman
Nov 11 at 15:53
Not fully clear that you want to display the response data in the Form input fields or in a table?
– Zollie
Nov 11 at 14:28
Not fully clear that you want to display the response data in the Form input fields or in a table?
– Zollie
Nov 11 at 14:28
@zollie in a table, the form is a separate part
– Yash Morar
Nov 11 at 14:32
@zollie in a table, the form is a separate part
– Yash Morar
Nov 11 at 14:32
OK, I am checking it and get back to you.
– Zollie
Nov 11 at 15:10
OK, I am checking it and get back to you.
– Zollie
Nov 11 at 15:10
1
1
You have double-encoded your data. You shouldn't put the JSON result from serialize into another dict which itself is serialized by JsonResponse.
– Daniel Roseman
Nov 11 at 15:53
You have double-encoded your data. You shouldn't put the JSON result from serialize into another dict which itself is serialized by JsonResponse.
– Daniel Roseman
Nov 11 at 15:53
add a comment |
1 Answer
1
active
oldest
votes
up vote
1
down vote
accepted
I just give you an example of how a table can be created in HTML from the javascript JSON string data what you provided above:
<div>
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th width="30%">Name</th>
<th width="50%">Description</th>
<th width="12%">price</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
</div>
<style>
table, td {
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var newProducts = {"products": "[{"model": "products.product", "pk": 2, "fields": {"name": "Bag", "description": "Carries items conspicuously ", "price": "10.99"}}, {"model": "products.product", "pk": 3, "fields": {"name": "iPhone 8 Plus", "description": "a mobile device from Apple", "price": "850.00"}}, {"model": "products.product", "pk": 8, "fields": {"name": "Shoes", "description": "For your feet", "price": "49.50"}}, {"model": "products.product", "pk": 9, "fields": {"name": "Gloves", "description": "For your hands", "price": "2.99"}}, {"model": "products.product", "pk": 10, "fields": {"name": "Blanket", "description": "Keep warm", "price": "13.79"}}, {"model": "products.product", "pk": 11, "fields": {"name": "Gown", "description": "Sleep time", "price": "25.99"}}]"};
var mainObj = JSON.parse(newProducts.products); // I created an object from the json response
// you can iterate over the javascript Object
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
And this is a simple table result of the above code:
I hope this can show you some direction. You can of course style the table (or create the table other ways) and you can access all of the other data studying and using this example.
So, you should just extend your Ajax with calling the added javascript function at success: which I placed in to your jQuery/javasript.
$(document).ready(function() {
$.ajax({
url: 'products/getProducts/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
jData = JSON.parse(data)
alert("got json products!");
tableFromResponse(jData);
}
});
});
function tableFromResponse(responseData) {
var mainObj = JSON.parse(responseData.products);
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
}
(of course, the lot of json.parse step could be left out from the code if it's causing trouble. Since I wrote the code without real response data from Django in this case).
Thank you - this worked!
– Yash Morar
Nov 12 at 20:58
add a comment |
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
1
down vote
accepted
I just give you an example of how a table can be created in HTML from the javascript JSON string data what you provided above:
<div>
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th width="30%">Name</th>
<th width="50%">Description</th>
<th width="12%">price</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
</div>
<style>
table, td {
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var newProducts = {"products": "[{"model": "products.product", "pk": 2, "fields": {"name": "Bag", "description": "Carries items conspicuously ", "price": "10.99"}}, {"model": "products.product", "pk": 3, "fields": {"name": "iPhone 8 Plus", "description": "a mobile device from Apple", "price": "850.00"}}, {"model": "products.product", "pk": 8, "fields": {"name": "Shoes", "description": "For your feet", "price": "49.50"}}, {"model": "products.product", "pk": 9, "fields": {"name": "Gloves", "description": "For your hands", "price": "2.99"}}, {"model": "products.product", "pk": 10, "fields": {"name": "Blanket", "description": "Keep warm", "price": "13.79"}}, {"model": "products.product", "pk": 11, "fields": {"name": "Gown", "description": "Sleep time", "price": "25.99"}}]"};
var mainObj = JSON.parse(newProducts.products); // I created an object from the json response
// you can iterate over the javascript Object
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
And this is a simple table result of the above code:
I hope this can show you some direction. You can of course style the table (or create the table other ways) and you can access all of the other data studying and using this example.
So, you should just extend your Ajax with calling the added javascript function at success: which I placed in to your jQuery/javasript.
$(document).ready(function() {
$.ajax({
url: 'products/getProducts/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
jData = JSON.parse(data)
alert("got json products!");
tableFromResponse(jData);
}
});
});
function tableFromResponse(responseData) {
var mainObj = JSON.parse(responseData.products);
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
}
(of course, the lot of json.parse step could be left out from the code if it's causing trouble. Since I wrote the code without real response data from Django in this case).
Thank you - this worked!
– Yash Morar
Nov 12 at 20:58
add a comment |
up vote
1
down vote
accepted
I just give you an example of how a table can be created in HTML from the javascript JSON string data what you provided above:
<div>
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th width="30%">Name</th>
<th width="50%">Description</th>
<th width="12%">price</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
</div>
<style>
table, td {
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var newProducts = {"products": "[{"model": "products.product", "pk": 2, "fields": {"name": "Bag", "description": "Carries items conspicuously ", "price": "10.99"}}, {"model": "products.product", "pk": 3, "fields": {"name": "iPhone 8 Plus", "description": "a mobile device from Apple", "price": "850.00"}}, {"model": "products.product", "pk": 8, "fields": {"name": "Shoes", "description": "For your feet", "price": "49.50"}}, {"model": "products.product", "pk": 9, "fields": {"name": "Gloves", "description": "For your hands", "price": "2.99"}}, {"model": "products.product", "pk": 10, "fields": {"name": "Blanket", "description": "Keep warm", "price": "13.79"}}, {"model": "products.product", "pk": 11, "fields": {"name": "Gown", "description": "Sleep time", "price": "25.99"}}]"};
var mainObj = JSON.parse(newProducts.products); // I created an object from the json response
// you can iterate over the javascript Object
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
And this is a simple table result of the above code:
I hope this can show you some direction. You can of course style the table (or create the table other ways) and you can access all of the other data studying and using this example.
So, you should just extend your Ajax with calling the added javascript function at success: which I placed in to your jQuery/javasript.
$(document).ready(function() {
$.ajax({
url: 'products/getProducts/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
jData = JSON.parse(data)
alert("got json products!");
tableFromResponse(jData);
}
});
});
function tableFromResponse(responseData) {
var mainObj = JSON.parse(responseData.products);
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
}
(of course, the lot of json.parse step could be left out from the code if it's causing trouble. Since I wrote the code without real response data from Django in this case).
Thank you - this worked!
– Yash Morar
Nov 12 at 20:58
add a comment |
up vote
1
down vote
accepted
up vote
1
down vote
accepted
I just give you an example of how a table can be created in HTML from the javascript JSON string data what you provided above:
<div>
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th width="30%">Name</th>
<th width="50%">Description</th>
<th width="12%">price</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
</div>
<style>
table, td {
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var newProducts = {"products": "[{"model": "products.product", "pk": 2, "fields": {"name": "Bag", "description": "Carries items conspicuously ", "price": "10.99"}}, {"model": "products.product", "pk": 3, "fields": {"name": "iPhone 8 Plus", "description": "a mobile device from Apple", "price": "850.00"}}, {"model": "products.product", "pk": 8, "fields": {"name": "Shoes", "description": "For your feet", "price": "49.50"}}, {"model": "products.product", "pk": 9, "fields": {"name": "Gloves", "description": "For your hands", "price": "2.99"}}, {"model": "products.product", "pk": 10, "fields": {"name": "Blanket", "description": "Keep warm", "price": "13.79"}}, {"model": "products.product", "pk": 11, "fields": {"name": "Gown", "description": "Sleep time", "price": "25.99"}}]"};
var mainObj = JSON.parse(newProducts.products); // I created an object from the json response
// you can iterate over the javascript Object
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
And this is a simple table result of the above code:
I hope this can show you some direction. You can of course style the table (or create the table other ways) and you can access all of the other data studying and using this example.
So, you should just extend your Ajax with calling the added javascript function at success: which I placed in to your jQuery/javasript.
$(document).ready(function() {
$.ajax({
url: 'products/getProducts/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
jData = JSON.parse(data)
alert("got json products!");
tableFromResponse(jData);
}
});
});
function tableFromResponse(responseData) {
var mainObj = JSON.parse(responseData.products);
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
}
(of course, the lot of json.parse step could be left out from the code if it's causing trouble. Since I wrote the code without real response data from Django in this case).
I just give you an example of how a table can be created in HTML from the javascript JSON string data what you provided above:
<div>
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th width="30%">Name</th>
<th width="50%">Description</th>
<th width="12%">price</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
</div>
<style>
table, td {
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var newProducts = {"products": "[{"model": "products.product", "pk": 2, "fields": {"name": "Bag", "description": "Carries items conspicuously ", "price": "10.99"}}, {"model": "products.product", "pk": 3, "fields": {"name": "iPhone 8 Plus", "description": "a mobile device from Apple", "price": "850.00"}}, {"model": "products.product", "pk": 8, "fields": {"name": "Shoes", "description": "For your feet", "price": "49.50"}}, {"model": "products.product", "pk": 9, "fields": {"name": "Gloves", "description": "For your hands", "price": "2.99"}}, {"model": "products.product", "pk": 10, "fields": {"name": "Blanket", "description": "Keep warm", "price": "13.79"}}, {"model": "products.product", "pk": 11, "fields": {"name": "Gown", "description": "Sleep time", "price": "25.99"}}]"};
var mainObj = JSON.parse(newProducts.products); // I created an object from the json response
// you can iterate over the javascript Object
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
And this is a simple table result of the above code:
I hope this can show you some direction. You can of course style the table (or create the table other ways) and you can access all of the other data studying and using this example.
So, you should just extend your Ajax with calling the added javascript function at success: which I placed in to your jQuery/javasript.
$(document).ready(function() {
$.ajax({
url: 'products/getProducts/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
jData = JSON.parse(data)
alert("got json products!");
tableFromResponse(jData);
}
});
});
function tableFromResponse(responseData) {
var mainObj = JSON.parse(responseData.products);
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
}
(of course, the lot of json.parse step could be left out from the code if it's causing trouble. Since I wrote the code without real response data from Django in this case).
edited Nov 11 at 18:45
answered Nov 11 at 17:11
Zollie
35915
35915
Thank you - this worked!
– Yash Morar
Nov 12 at 20:58
add a comment |
Thank you - this worked!
– Yash Morar
Nov 12 at 20:58
Thank you - this worked!
– Yash Morar
Nov 12 at 20:58
Thank you - this worked!
– Yash Morar
Nov 12 at 20:58
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249365%2fget-data-from-django-model-and-display-in-a-html-table-using-ajax%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Not fully clear that you want to display the response data in the Form input fields or in a table?
– Zollie
Nov 11 at 14:28
@zollie in a table, the form is a separate part
– Yash Morar
Nov 11 at 14:32
OK, I am checking it and get back to you.
– Zollie
Nov 11 at 15:10
1
You have double-encoded your data. You shouldn't put the JSON result from serialize into another dict which itself is serialized by JsonResponse.
– Daniel Roseman
Nov 11 at 15:53