What I need
I'm trying to find a way to send a multi layered dictionary via AJAX to my server, including a JavaScript seralised form with the use of serialize()
.
The issue
When I use data: frm.serialize();
. It's a single layered json and it is easily parsed when returned to server with result:
<QueryDict: {'csrfmiddlewaretoken': ['6aTZ7xey90sczae15069ZlbIiE7gVWW69RyeJBptUxadbgnBo8t8R0Nskg8S8Jzb', '6aTZ7xey90sczae15069ZlbIiE7gVWW69RyeJBptUxadbgnBo8t8R0Nskg8S8Jzb'], 'days': ['Mon', 'Wed'], 'no_weeks': ['1']}>
Then when using a nested dictionary with
data: {'form':frm.serialize(),'additional_data':12,'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()}```
I get:
<QueryDict: {'form': ['csrfmiddlewaretoken=IF2D4vTBjaQSsrE4oY3Lb36jekPB5nZbLmHSGz4w4HyT4xNEH6qK3II3gWQdiaCg&days=Mon&days=Thu&no_weeks=2&csrfmiddlewaretoken=IF2D4vTBjaQSsrE4oY3Lb36jekPB5nZbLmHSGz4w4HyT4xNEH6qK3II3gWQdiaCg'], 'additional_data': ['12'], 'csrfmiddlewaretoken': ['IF2D4vTBjaQSsrE4oY3Lb36jekPB5nZbLmHSGz4w4HyT4xNEH6qK3II3gWQdiaCg']}>
What i've tried
I have attempted with use of this answer to use urllib
to parse the form section of the data into a separate variable. Like so:
x = parse_qs(urllib.parse.urlparse(request.POST['form']).query)
This returns an empty dicitonary.
Code
HTML
<form method="post" id="replicate_form">
[..more code]
</form>
Javscript
function send_replication_data() {
var frm = $('#replicate_form')
var form_server_response = submit_formdata(frm)
}
// parent function to handle replcation form saving
$('#create_replicate_booking_button').on('click', function() {
send_replication_data()
});
// submit booking data ajax
function submit_formdata(frm) {
var tmp = $.ajax({
type: frm.attr('method'),
async:false,
url: window.location.href,
data: {'form':frm.serialize(),
'additional_data':12,
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()}
});
return tmp.responseJSON;
}
Possibly I could somehow make use of whatever Django is doing in it's middleware to a parse the form data in the first scenario?