my question is, what´s the better way to pass a value from a javascript function to django view.
I have a template where I get a value through a javascript function, and I want to pass that value to a django view.
The question is pretty general, but here's one way of doing it. You could use jQuery to make your AJAX call like this:
$.ajax({type: 'POST',
url: '/fetch_data/', // some data url
data: {param: 'hello', another_param: 5}, // some params
success: function (response) { // callback
if (response.result === 'OK') {
if (response.data && typeof(response.data) === 'object') {
// do something with the successful response.data
// e.g. response.data can be a JSON object
}
} else {
// handle an unsuccessful response
}
}
});
And your Django view would be something like this:
def fetch_data(request):
if request.is_ajax():
# extract your params (also, remember to validate them)
param = request.POST.get('param', None)
another_param = request.POST.get('another param', None)
# construct your JSON response by calling a data method from elsewhere
items, summary = build_my_response(param, another_param)
return JsonResponse({'result': 'OK', 'data': {'items': items, 'summary': summary}})
return HttpResponseBadRequest()
Many details are obviously omitted here, but you can use this as a guideline.
Two ways here: