最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to properly get form data with JQuery and formData - Stack Overflow

programmeradmin0浏览0评论

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).

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

?>

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).

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

?>
Share Improve this question edited Mar 22, 2015 at 15:26 Jason 15.3k23 gold badges86 silver badges118 bronze badges asked Mar 22, 2015 at 14:48 André OliveiraAndré Oliveira 1,1214 gold badges22 silver badges53 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12
 $.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

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;
   }
发布评论

评论列表(0)

  1. 暂无评论