I'm using ajax to pass data to a view for save in database. In javascript the data look correct but in the view is null. Read the comments in code for other questions and informations
My javascript
:
...
var changed_element=[];
var changed_value=[];
document.getElementById('tabella').addEventListener('change', function(event){
...
changed_element.push(element); //list of list of string
changed_value.push(elem[elem.value].text); //list of string
...
});
document.getElementById('btn-save').addEventListener('click', function() {
console.log('changed_element', changed_element) //print the right value
$.ajax({type: 'POST',
url: '/salva-conoscenze-rapporti/',
data: {
changed_element: changed_element,
changed_value: changed_value //<= comma?
},
success: function(msg) {
console.log(msg) //prints 'It works'
document.getElementById('btn-save').style.display = 'none';
} //<= comma?
});
});
My view
:
@staff_member_required
@ensure_csrf_cookie #I need this?
def salva_conoscenze_rapporti(request):
if request.is_ajax():
changed_element = request.POST.get('changed_element', None)
changed_value = request.POST.get('changed_value', None)
msg='it works'
print(changed_element) #prints None instead of array
print(changed_value)
else:
msg="it doesn't work"
return HttpResponse(msg)
My template base.html
:
...
<script>
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
</script>
...
My template
:
{% extends 'base.html' %}
...
Basically print(changed_element)
should gives the data instead gives None
.
My MIDDLEWARE_CLASSES
in settings.py
:
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
My variables:
changed_element=[ [ "conoscenza", "Cliente1", "Cliente2" ] ];
changed_value=[ "Generale" ];
console.log(changed_element)
gives: Array [ Array[3] ]
To get the cookie you also can use with jQuery
And then, I'll correcting your script.
Or like this one:
In your
views.py
Hope it can help.