I would like to pass some data from my Python view function to a JS script using HTML. That's my view function
def home(request):
if request.method == 'POST':
params = GameOfLifeForm(request.POST)
if params.is_valid():
starting_grid = get_starting_grid(params.cleaned_data)
to_html = {
'animation': True,
'gameoflifeform': params,
'start_grid': starting_grid,
}
else:
to_html = {
'animation': False,
'warning_msg': 'Something went wrong. Try once again.'
}
return render(request, 'get_animations/home.html', to_html)
else:
form = GameOfLifeForm()
return render(request, 'get_animations/home.html', {'gameoflifeform': form})
My form contains four parameters, one of them is called iterations and that is the one I would like to pass to JS script. Moreover I would like to pass start_grid.
I tried to do it in the following way in my HTML file
{{ start_grid | json_script:"start-grid" }}
<script
type="text/javascript"
src="{% static 'js/runGameOfLife.js' %}"
></script>
Then in my JS script I wrote
var startGrid = JSON.parse(document.getElementById("start-grid").textContent);
console.log(startGrid);
Worked perfectly, I got the grid printed out in my console. Similar I could grab iterations from HTML
{{ gameoflifeform.iterations.value | json_script:"iterations"}}
<script
type="text/javascript"
src="{% static 'js/runGameOfLife.js' %}"
></script>
When I tried to add both variables into my JS script it didn't work.
{{ gameoflifeform.iterations.value | json_script:"iterations"}}
{{ start_grid | json_script:"start-grid" }}
<script
type="text/javascript"
src="{% static 'js/runGameOfLife.js' %}"
></script>
How can I pass several variables into my JS script? What would be the best way of doing it?
Best to use some combination of ajax and view functions, if you learn this pattern you can accomplish a lot:
views.py
def my_view_function(request):
''' this method accepts data from the front end,
processes it, and returns a response '''
# unpack post request:
first_value = request.POST.get('first_key')
# do some logic:
...
# pack response
response = {
"second_key" : "second_value"
}
# return a json response:
return JsonResponse(response)
scripts.js
function post_request() {
/* set an event to trigger this method
this method will then send data to the backend
and process the response */
// send an ajax post request:
$.ajax({
type : 'POST',
url : 'the_url',
data : {
first_key : 'first_value'
},
success : function(response) {
// unpack response
second_value = response.second_key
// do some logic
...
}
});
}
Once you understand this, you will be able to seamlessly pass data back and forth between the frontend and backend. Let me know if you need more details.