I want to render a data frame to the front-end so that I can create a table on my html page.
Usually, if I use simple render (without ajax involves), I transfer it to a list of json data and then render it to html page:
my_function.py:
def df_to_json(df):
json_records = df.reset_index().to_json(orient ='records')
data = []
data = json.loads(json_records)
return data
The json data look like this:
[{"category":0, "sales":135, "cost": 197, "em_id":12},
{"category":0, "sales":443, "cost": 556, "em_id":12},
{"category":2, "sales":1025, "cost": 774, "em_id":15},...]
Then in my views.py and based.html page:
views.py:
def home(request):
dict_search = request.GET.get('inputtxt_from_html')
df = my_function.myfunction1(dict_search)
df_json = my_function.df_to_json(df)
return render(request, 'base.html', {'df_json': df_json})
based.html:
<div class="container">
<table class="table table-dark table-striped" id='table1'>
<tbody>
{% if df_json%}
{% for i in df_json%}
<tr>
<td>{{i.sales}}</td>
<td>{{i.cost}}</td>
<td>{{i.em_id}}</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
</div>
The problem now is that I want to do something like above but this time the input is from ajax.
And it seems like I cannot directly get the render results {{df_json}} for my html page. I tried to do something in the "success:" part of my ajax, but it either show "Object" or just text.
How shouldI code in "success:" part to get the entire {{df_json}}, so that I don't have to change my based.html page? Or acturally I have to do something different in all view, based, ajax pages?
my_ajax.js:
$(document).ready(function(){
$("#button1").click(function() {
$.ajax({
url: '',
type: 'GET',
data: {
inputtxt_from_html: $("#input_field").val()
},
success: function(response){
-- I don't know how to write. belowing is just example
$("#table1").append('<li>' + response.json_dict + '</li>')
}
});
});
});
New view.py:
def home(request):
dict_search = request.GET.get('inputtxt_from_html')
if request.is_ajax():
df = my_function.myfunction1(dict_search)
df_json = my_function.df_to_json(df)
return JsonResponse({'df_json': df_json}, status=200)
return render(request, 'base.html')
Thank you