Reputation: 255
Summary: I am creating a web page which shows the results of user selections. I have two files. html and jquery. I have created a variable reports_array = [ ] which collects all the selections of user when "Done" button is clicked.
Issue: I have to pass reports_array[ ] values to the django view.
Here is the code for jquery
.on('click','.done', function(){
var report_array = [];
report_array.push(
{
Layer_Table: layer_array,
Benefits_Table: benefits_array,
Map_Layer_selection: save_selection_layer,
Map_Benefits_selection: save_selection_benefits,
});
console.log(report_array);
Here is the code for view.py
def done(request):
template = loader.get_template('maps/done.html')
context = RequestContext(request, {
'reports_link': report_array, //I believe this is not correct.
})
return HttpResponse(template.render(context))
how to pass report_array from jquery to this "context"...???? assume done.html contains following code
<head>
<title>Reports</title>
</head>
<body>
<p>{{ reports_link }}</p>
</body>
I am new to django interface. Assume url.py is correct. I am looking for logic that i am missing here.
Thanks in advance
Upvotes: 2
Views: 3597
Reputation: 26
I am not sure I understood how you want to present the report array. But to pass JQuery array to Django view you can use AJAX call to Django URL
var obj = {'report_array': report_array}
$.ajax({
type: 'POST',
url: '/DESTINATION_URL/',
contentType: 'application/json; charset=utf-8', //EDITED
data: JSON.stringify(obj),
success: function(data) {
$('body').html(data); //EDITED
},
error: function(rs, e) {
alert(rs.responseText);
}
});
Then in your views.py
import json
from django.template.loader import render_to_string
def done(request):
params = json.loads(request.body)
report_array = params['report_array']
html_data = render_to_string('maps/done.html', {'reports_link': report_array})
return HttpResponse(html_data)
Then your done.html can just be this:
<body>
<p>{{ reports_link }}</p>
</body>
This way AJAX will render your page to show the report_array on success. So it will change the content of body without reloading the page.
Upvotes: 1