How to upload a file using Ajax on POST?









up vote
7
down vote

favorite
1












I know the topics aren't missing on this subject that's why I looked into a huge amount of posts about this topic and couldn't find something that'd satisfy me, so I'm trying to build it by myself.



All I want to do is to upload a file using Ajax with Django to avoid page refresh.



Here's what I did :



basic_upload.html :



<form method="post" id="creationOptionsForm" enctype="multipart/form-data">
% csrf_token %

<div>
form.name.errors
form.name
</div>

<div>
form.email.errors
form.email
</div>

<div>
form.logo.errors
form.logo
</div>

<input type="submit" value="submit">
</form>


Ajax.js :



$(document).on('submit', '#creationOptionsForm', function(e)
e.preventDefault();

var form_data = new FormData();
form_data.append('file', $('#creationOptionsForm').get(0).files);

$.ajax(
type:'POST',
url:'/designer/results/',
processData: false,
contentType: false,
data:
organisation:$('#id_organisation').val(),
email:$('#id_email').val(),
logo:form_data,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
,
);
);


Views.py :



def creationResult(request):
if request.method == 'POST':
form = UserInfos(request.POST, request.FILES)
if form.is_valid():
photo = form.save()
...
...


(forms.py & urls.py are correctly configured, it is not necessary to include them).



I guess there's an issue with the way I do on the ajax.js since on debug (pdb) request.POST return every datas except logo.



What am I doing incorectly ?










share|improve this question



























    up vote
    7
    down vote

    favorite
    1












    I know the topics aren't missing on this subject that's why I looked into a huge amount of posts about this topic and couldn't find something that'd satisfy me, so I'm trying to build it by myself.



    All I want to do is to upload a file using Ajax with Django to avoid page refresh.



    Here's what I did :



    basic_upload.html :



    <form method="post" id="creationOptionsForm" enctype="multipart/form-data">
    % csrf_token %

    <div>
    form.name.errors
    form.name
    </div>

    <div>
    form.email.errors
    form.email
    </div>

    <div>
    form.logo.errors
    form.logo
    </div>

    <input type="submit" value="submit">
    </form>


    Ajax.js :



    $(document).on('submit', '#creationOptionsForm', function(e)
    e.preventDefault();

    var form_data = new FormData();
    form_data.append('file', $('#creationOptionsForm').get(0).files);

    $.ajax(
    type:'POST',
    url:'/designer/results/',
    processData: false,
    contentType: false,
    data:
    organisation:$('#id_organisation').val(),
    email:$('#id_email').val(),
    logo:form_data,
    csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
    ,
    );
    );


    Views.py :



    def creationResult(request):
    if request.method == 'POST':
    form = UserInfos(request.POST, request.FILES)
    if form.is_valid():
    photo = form.save()
    ...
    ...


    (forms.py & urls.py are correctly configured, it is not necessary to include them).



    I guess there's an issue with the way I do on the ajax.js since on debug (pdb) request.POST return every datas except logo.



    What am I doing incorectly ?










    share|improve this question

























      up vote
      7
      down vote

      favorite
      1









      up vote
      7
      down vote

      favorite
      1






      1





      I know the topics aren't missing on this subject that's why I looked into a huge amount of posts about this topic and couldn't find something that'd satisfy me, so I'm trying to build it by myself.



      All I want to do is to upload a file using Ajax with Django to avoid page refresh.



      Here's what I did :



      basic_upload.html :



      <form method="post" id="creationOptionsForm" enctype="multipart/form-data">
      % csrf_token %

      <div>
      form.name.errors
      form.name
      </div>

      <div>
      form.email.errors
      form.email
      </div>

      <div>
      form.logo.errors
      form.logo
      </div>

      <input type="submit" value="submit">
      </form>


      Ajax.js :



      $(document).on('submit', '#creationOptionsForm', function(e)
      e.preventDefault();

      var form_data = new FormData();
      form_data.append('file', $('#creationOptionsForm').get(0).files);

      $.ajax(
      type:'POST',
      url:'/designer/results/',
      processData: false,
      contentType: false,
      data:
      organisation:$('#id_organisation').val(),
      email:$('#id_email').val(),
      logo:form_data,
      csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
      ,
      );
      );


      Views.py :



      def creationResult(request):
      if request.method == 'POST':
      form = UserInfos(request.POST, request.FILES)
      if form.is_valid():
      photo = form.save()
      ...
      ...


      (forms.py & urls.py are correctly configured, it is not necessary to include them).



      I guess there's an issue with the way I do on the ajax.js since on debug (pdb) request.POST return every datas except logo.



      What am I doing incorectly ?










      share|improve this question















      I know the topics aren't missing on this subject that's why I looked into a huge amount of posts about this topic and couldn't find something that'd satisfy me, so I'm trying to build it by myself.



      All I want to do is to upload a file using Ajax with Django to avoid page refresh.



      Here's what I did :



      basic_upload.html :



      <form method="post" id="creationOptionsForm" enctype="multipart/form-data">
      % csrf_token %

      <div>
      form.name.errors
      form.name
      </div>

      <div>
      form.email.errors
      form.email
      </div>

      <div>
      form.logo.errors
      form.logo
      </div>

      <input type="submit" value="submit">
      </form>


      Ajax.js :



      $(document).on('submit', '#creationOptionsForm', function(e)
      e.preventDefault();

      var form_data = new FormData();
      form_data.append('file', $('#creationOptionsForm').get(0).files);

      $.ajax(
      type:'POST',
      url:'/designer/results/',
      processData: false,
      contentType: false,
      data:
      organisation:$('#id_organisation').val(),
      email:$('#id_email').val(),
      logo:form_data,
      csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
      ,
      );
      );


      Views.py :



      def creationResult(request):
      if request.method == 'POST':
      form = UserInfos(request.POST, request.FILES)
      if form.is_valid():
      photo = form.save()
      ...
      ...


      (forms.py & urls.py are correctly configured, it is not necessary to include them).



      I guess there's an issue with the way I do on the ajax.js since on debug (pdb) request.POST return every datas except logo.



      What am I doing incorectly ?







      jquery ajax django






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 22 '17 at 20:53

























      asked Jun 22 '17 at 19:39









      Nuri Katsuki

      1,90252552




      1,90252552






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          11
          down vote



          accepted










          The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES



          Try this:



          $(document).on('submit', '#creationOptionsForm', function(e)
          e.preventDefault();

          var form_data = new FormData($('#creationOptionsForm')[0]);
          $.ajax(
          type:'POST',
          url:'/designer/results/',
          processData: false,
          contentType: false,
          async: false,
          cache: false,
          data : form_data,
          success: function(response)


          );
          );


          Update:



          basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.



          While cache will force browser to not cache uploaded data to get updated data in ajax request



          Official Documentation here






          share|improve this answer






















          • Wonderful, what does async & cache do ?
            – Nuri Katsuki
            Jun 22 '17 at 20:56






          • 1




            @Lindow updated answer, hope that helps :)
            – Mahesh Singh Chouhan
            Jun 22 '17 at 21:06






          • 4




            You do not need async: false anymore (on the contrary: if you set it, you'll get a warning in the Chrome console)
            – Olivier Pons
            Jan 12 at 15:03










          • Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org.
            – Taioli Francesco
            May 29 at 15:48










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f44708023%2fhow-to-upload-a-file-using-ajax-on-post%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          11
          down vote



          accepted










          The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES



          Try this:



          $(document).on('submit', '#creationOptionsForm', function(e)
          e.preventDefault();

          var form_data = new FormData($('#creationOptionsForm')[0]);
          $.ajax(
          type:'POST',
          url:'/designer/results/',
          processData: false,
          contentType: false,
          async: false,
          cache: false,
          data : form_data,
          success: function(response)


          );
          );


          Update:



          basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.



          While cache will force browser to not cache uploaded data to get updated data in ajax request



          Official Documentation here






          share|improve this answer






















          • Wonderful, what does async & cache do ?
            – Nuri Katsuki
            Jun 22 '17 at 20:56






          • 1




            @Lindow updated answer, hope that helps :)
            – Mahesh Singh Chouhan
            Jun 22 '17 at 21:06






          • 4




            You do not need async: false anymore (on the contrary: if you set it, you'll get a warning in the Chrome console)
            – Olivier Pons
            Jan 12 at 15:03










          • Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org.
            – Taioli Francesco
            May 29 at 15:48














          up vote
          11
          down vote



          accepted










          The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES



          Try this:



          $(document).on('submit', '#creationOptionsForm', function(e)
          e.preventDefault();

          var form_data = new FormData($('#creationOptionsForm')[0]);
          $.ajax(
          type:'POST',
          url:'/designer/results/',
          processData: false,
          contentType: false,
          async: false,
          cache: false,
          data : form_data,
          success: function(response)


          );
          );


          Update:



          basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.



          While cache will force browser to not cache uploaded data to get updated data in ajax request



          Official Documentation here






          share|improve this answer






















          • Wonderful, what does async & cache do ?
            – Nuri Katsuki
            Jun 22 '17 at 20:56






          • 1




            @Lindow updated answer, hope that helps :)
            – Mahesh Singh Chouhan
            Jun 22 '17 at 21:06






          • 4




            You do not need async: false anymore (on the contrary: if you set it, you'll get a warning in the Chrome console)
            – Olivier Pons
            Jan 12 at 15:03










          • Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org.
            – Taioli Francesco
            May 29 at 15:48












          up vote
          11
          down vote



          accepted







          up vote
          11
          down vote



          accepted






          The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES



          Try this:



          $(document).on('submit', '#creationOptionsForm', function(e)
          e.preventDefault();

          var form_data = new FormData($('#creationOptionsForm')[0]);
          $.ajax(
          type:'POST',
          url:'/designer/results/',
          processData: false,
          contentType: false,
          async: false,
          cache: false,
          data : form_data,
          success: function(response)


          );
          );


          Update:



          basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.



          While cache will force browser to not cache uploaded data to get updated data in ajax request



          Official Documentation here






          share|improve this answer














          The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES



          Try this:



          $(document).on('submit', '#creationOptionsForm', function(e)
          e.preventDefault();

          var form_data = new FormData($('#creationOptionsForm')[0]);
          $.ajax(
          type:'POST',
          url:'/designer/results/',
          processData: false,
          contentType: false,
          async: false,
          cache: false,
          data : form_data,
          success: function(response)


          );
          );


          Update:



          basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.



          While cache will force browser to not cache uploaded data to get updated data in ajax request



          Official Documentation here







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 22 '17 at 21:05

























          answered Jun 22 '17 at 19:52









          Mahesh Singh Chouhan

          2,1901922




          2,1901922











          • Wonderful, what does async & cache do ?
            – Nuri Katsuki
            Jun 22 '17 at 20:56






          • 1




            @Lindow updated answer, hope that helps :)
            – Mahesh Singh Chouhan
            Jun 22 '17 at 21:06






          • 4




            You do not need async: false anymore (on the contrary: if you set it, you'll get a warning in the Chrome console)
            – Olivier Pons
            Jan 12 at 15:03










          • Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org.
            – Taioli Francesco
            May 29 at 15:48
















          • Wonderful, what does async & cache do ?
            – Nuri Katsuki
            Jun 22 '17 at 20:56






          • 1




            @Lindow updated answer, hope that helps :)
            – Mahesh Singh Chouhan
            Jun 22 '17 at 21:06






          • 4




            You do not need async: false anymore (on the contrary: if you set it, you'll get a warning in the Chrome console)
            – Olivier Pons
            Jan 12 at 15:03










          • Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org.
            – Taioli Francesco
            May 29 at 15:48















          Wonderful, what does async & cache do ?
          – Nuri Katsuki
          Jun 22 '17 at 20:56




          Wonderful, what does async & cache do ?
          – Nuri Katsuki
          Jun 22 '17 at 20:56




          1




          1




          @Lindow updated answer, hope that helps :)
          – Mahesh Singh Chouhan
          Jun 22 '17 at 21:06




          @Lindow updated answer, hope that helps :)
          – Mahesh Singh Chouhan
          Jun 22 '17 at 21:06




          4




          4




          You do not need async: false anymore (on the contrary: if you set it, you'll get a warning in the Chrome console)
          – Olivier Pons
          Jan 12 at 15:03




          You do not need async: false anymore (on the contrary: if you set it, you'll get a warning in the Chrome console)
          – Olivier Pons
          Jan 12 at 15:03












          Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org.
          – Taioli Francesco
          May 29 at 15:48




          Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org.
          – Taioli Francesco
          May 29 at 15:48

















           

          draft saved


          draft discarded















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f44708023%2fhow-to-upload-a-file-using-ajax-on-post%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Top Tejano songwriter Luis Silva dead of heart attack at 64

          ReactJS Fetched API data displays live - need Data displayed static

          政党