0

To implement a non-refreshing effect, I decide to use $.post() However, I need to send csrf token also, as a result, I cannot send only input contents of my form. Here's my code at .js, but the JSON.stringify($(this)) gives me things I don't want at the views.py back-end.

.js

$('#my-form').submit(function(e){
    e.preventDefault();
    url=$(this).attr('action');
    data=JSON.stringify($(this))
    $.post(url,{'data':data,'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()},function(data_returned){
        alert('submit done');
    });
});

at my views.py

print("data:"+json.loads(str(request.POST['data'])))

which gives me something like these:

{"0":{"0":{},"1":{},"2":{"0":{},"1":{},"2":{}},"3":{},"4":{},"5":{},"6":{},"7":{},"8":{},"9":{},"10":{},"jQuery112402971640175601502":28},"context":{"0":{},"1":{},"2":{"0":{},"1":{},"2":{}},"3":{},"4":{},"5":{},"6":{},"7":{},"8":{},"9":{}," 10":{},"jQuery112402971640175601502":28},"length":1}

Any suggestion? Thanks!

Cindy
  • 315
  • 2
  • 19
  • I found a nice Q&A :https://stackoverflow.com/questions/11647715/how-to-submit-form-without-refreshing-page-using-django-ajax-jquery – Cindy Jan 25 '19 at 01:17
  • There's no need to put an extra 'csrfmiddlewaretoken' . – Cindy Jan 25 '19 at 02:33

0 Answers0