0

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?

1 Answer 1

1

The .serialize() method creates a text string in standard URL-encoded notation.

You could use urllib.parse.parse_qs to parse a query string(form data sent to server by GET) or request.POST['form'] since it uses the same encoding.

Query strings are element of urls, while request.POST['form'] has no attribute called query

from urllib import parse
x = parse.parse_qs(request.POST['form']).query)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.