Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly get form data with JQuery and formData

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 Postenter image description here

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

?>
like image 499
André Oliveira Avatar asked Jan 09 '23 16:01

André Oliveira


2 Answers

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

like image 184
tech-gayan Avatar answered Jan 14 '23 19:01

tech-gayan


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;
   }
like image 39
Zahra Badri Avatar answered Jan 14 '23 17:01

Zahra Badri