4

I am trying to upload some form data using ajax and php but for some reason my data is not being catch or passed.

Here is what I have:

form.html ( basic form with 3 text inputs and 1 file)

<form class="form" id="superform" action="nada.php" method="post" enctype="multipart/form-data">
          <div class="form-group">
              <label for="tituloQuiz">Resultado:</label>
              <input type="text" class="form-control resultado" id="titulo" name="titulo" placeholder="Ex: Paris">
          </div>

          <div class="form-group">
              <label for="desc">Descrição do Site:</label>
              <textarea  class="form-control" id="desc" name="descricao" placeholder="Ex:"></textarea>
          </div>

          <div class="form-group">
              <label for="desc">OG FB DESC:</label>
              <textarea  class="form-control" id="facedes" name="descricao" placeholder="facebook description"></textarea>
          </div>

          <div class="form-group">
            <label for="imggrande">Imagem</label>
            <input type="file" id="imggrande" name="imgres">
            <p class="help-block">Imagem usada na página de resultado e Facebook 600 x 400.</p>
          </div>
          <button type="button" class="btn btn-primary btn-lg addres">Adicionar Resultado</button>
          <button type="button" class="btn btn-danger btn-lg">Próxima Etapa</button>
       </form>

And here is the JS that makes the ajax call: myjs.js

 $("document").ready(function(){
     $('.row').on('click','.addres',function(){
         console.log('Click Detectado');
         var formulario = $('#superform');
         var formData = new FormData(formulario);

          $.ajax({

                  type: "POST",
                  url: "addres.php",
                  data: formData,
                  async: false,
                  success: function(data) {
                        console.log('Funcionou');
                  },
                  error: function(data) {
                      console.log('Erro no formulario');
                  },
                  cache: false,
                  contetType: false,
                  processData: false
          });


     });
 });

Nothing is being passed and the POST call is empty (See screenshots below). Empty Post enter image description here

**addres.php**
<?php
   var_dump($_FILES);
   var_dump($_POST);

?>
Jason
  • 15,017
  • 23
  • 85
  • 116
André Oliveira
  • 1,105
  • 4
  • 20
  • 53

2 Answers2

11
 $.ajax({
    url: 'address.php', 
    type: 'POST',
    data: new FormData($('#superform')[0]), // The form with the file    inputs.
    processData: false,                          // Using FormData, no need to process data.
    contentType:false
  }).done(function(){
     console.log("Success: Files sent!");
  }).fail(function(){
     console.log("An error occurred, the files couldn't be sent!");
});

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multi-part/form one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

read from php using

 $_FILES['file-0']

(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)

Additional info: See for yourself the difference of how your formData is passed to your php page by using console.log().

    var formData = new FormData($('#superform')[0]);
    console.log(formData);

    var formDataSerialized = $('#superform').serialize();
    console.log(formDataSerialized);

Hope this helps.

extra information read this upload files asynchronously

Note : formData doesn't work in IE 9

Community
  • 1
  • 1
tech-gayan
  • 1,373
  • 1
  • 10
  • 25
  • Thanks iceburg, now the data is being passed, but the $_FILES is empty. Any on how i access the data on the php side, normally i would use $_POST['titulo'] for example, but this is not working. – André Oliveira Mar 22 '15 at 15:41
  • are you getting the file name. try with edited version. – tech-gayan Mar 22 '15 at 15:47
  • Yes, but is in the var_dump($_POST); – André Oliveira Mar 22 '15 at 15:51
  • @Iceburg: You sure that `contentType:false` is a good idea here? According to docs it makes jQuery send no `Content-Type` header at all, but a file upload would required `multipart/form-data`. – CBroe Mar 22 '15 at 15:54
  • 1
    @CBroe contentType option to false is used for multipart/form-data forms that pass files. When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multi-part/form one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail. According to http://stackoverflow.com/questions/20795449/jquery-ajax-form-submission-enctype-multipart-form-data-why-does-contentt – André Oliveira Mar 22 '15 at 16:05
  • @André: Thanks, I wasn’t aware of that. Have you re-checked in developer tools to see what does actually get send now? Does that look o.k., compared to what you would get when the form is send “normally”, without AJAX? – CBroe Mar 22 '15 at 16:09
  • @André: I konw it's an old post but i am still hoping to get an answer. Why do we have to select an index;i.e; `new FormData($('#superform')[0])` with an ID selector while creating FormData object whereas an ID selector returns only one object provided that ID has been used only once? – Yeasir Arafat Majumder Jul 25 '17 at 02:23
1

You can use .serializeArray() to get the data in array format and then convert it into an object. like this:

    function getFormData(formId) {
       let formData = {};
       let inputs = $('#'+formId).serializeArray();
       $.each(inputs, function (i, input) {
          formData[input.name] = input.value;
      });
      return formData;
   }
Zahra Badri
  • 1,656
  • 1
  • 17
  • 28