简体   繁体   中英

How to populate a django form in a POST request with data from an ajax call?

I'm sending form data via an ajax call after user hits submit button and then handling this request in my views, but the form is empty. How can I populate the form?

This is my code:

My JS file:

var csrftoken = getCookie('csrftoken');  //getCookie is a csrf_token generator
var form = $(this).closest('form')
$.ajax({
        url: form.attr("action"),
        data: {        // if I change this line to data: form.serialize(), it works fine!
            csrfmiddlewaretoken : csrftoken,
            form: form.serialize(),  
    },
        type: form.attr("method"),
        dataType: 'json',
        success: function (data)
        {
            //Do a bunch of stuff here
        }
})

My views:

def task_edit(request, pk):
    task = get_object_or_404(Task, pk=pk)

    if request.method == 'POST':
        task_form = NewTaskForm(request.POST) # This is empty!

    else:
        task_form = NewTaskForm(instance=task) # This for populating the edit modal, works fine!

I'm not doing the data: form.serialize() because I need to send additional data with the ajax request. How do I get this working?

You can write as below:-

$form_data = $("#idofform").serialize();

And then in ajax

data : $form_data+'&key=value',

You can use services like https://www.formkeep.com to capture form data using AJAX.

This may be a good idea if you are already using a JavaScript framework, you want to add validation logic, or you don't want to redirect the user after they submit the form.

You can submit to FormKeep using a standard AJAX request. To ensure the request does not cause a redirect, be sure to set the Accept header to application/javascript.

Given the following form:

<form id="newsletter-signup" action="http://formkeep.com/f/exampletoken" method="POST" accept-charset="UTF-8">
    <input type="hidden" name="utf8" value="✓">
    <input name="email" type="email">
    <input value="Submit" type="submit">
</form>

Here's an example of how to submit a form with jQuery:

$(function() {
   $('#newsletter-signup').submit(function(event) {
event.preventDefault();

var formEl = $(this);
var submitButton = $('input[type=submit]', formEl);

$.ajax({
  type: 'POST',
  url: formEl.prop('action'),
  accept: {
    javascript: 'application/javascript'
  },
  data: formEl.serialize(),
  beforeSend: function() {
    submitButton.prop('disabled', 'disabled');
  }
}).done(function(data) {
  submitButton.prop('disabled', false);
});
});
});

That's it. Once your data is securely captured in FormKeep you can easily store it, manage it or connect it with 1000s of other systems like Google Docs and Hubspot and Mailchimp.

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