简体   繁体   中英

How to send json serialize data from a form to ajax using django

Currently, I'm sending the data via code in this way and it's working but how can I send the entire form in json?

Code :

 $.ajax({
         url : window.location.href, // the endpoint,commonly same url
         type : "POST", // http method
         data : { csrfmiddlewaretoken : csrftoken,
         email : email,
         password : password,
         username : username,
         dob : dob,
 }, // data sent with the post request

I want to send and retrieve everything including csrfmiddlewaretoken using formdata json.

I have tried something similar to that :

    var formData = new FormData($('#my_form');
    formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

 $.ajax({
         url : window.location.href, // the endpoint,commonly same url
         type : "POST", // http method
         data : formData, // data sent with the post request

But, this does not work for some reason. How can I get it to work?

you need to send json serialized form data as one paramater and csrf token as another parameter because every POST request expects a csrf token in it.

    csrfmiddlewaretoken = $("#add_member_Form").find("input[name='csrfmiddlewaretoken']" ).val();
    formData = $('#add_member_Form').serializeArray();
    formData = JSON.stringify(formData);
    $.ajax({
        url : url,
        data : {
            "csrfmiddlewaretoken" : csrfmiddlewaretoken,
            "formData" : formData
        },
        method: "POST",
        dataType : "json",

At server side in your view, you need to deserialize the data.

form_data_dict = {}
form_data_list = json.loads(form_data)
for field in form_data_list:
    form_data_dict[field["name"]] = field["value"]
return form_data_dict

You could grab the form data using serializeArray function in jQuery, then convert it into dictionary and send as post data.

The serializeArray function output would be something like,

{ 
    'name': 'the_name',
    'value': 'the_value'
}

Then, you would have to convert it to the dictionary or json format. Write a global function for that,

function objectifyForm(formArray) {
    var returnArray = {};
    for (var i=0;i<formArray.length;i++) {
        if (formArray[i].value) {
            returnArray[formArray[i].name] = formArray[i].value;
        }
    }
    return returnArray;
}

Call it whenever you have to grab the form data,

var formData = $('#my_form').serializeArray();
formData = objectifyForm(formData);
$.ajax({ 
        url : window.location.href, // the endpoint,commonly same url 
        type : "POST", // http method
        data : formData, 
        success: blaah,
        error: bleeh,
    });

It would be much less effort than having to decode the dictionary every time from the server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM