File field with Jquery

Asked

Viewed 1,236 times

0

I’m creating an upload through a modal this way:

<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header btn-primary">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">ALTERAR FOTO</h4>
      </div>
      <div class="modal-body">
          <form method="post" id="form-upload" novalidate enctype="multipart/form-data">
               <label for="email">Tamanho da imagem: 1170 x 300</label>
               <div class="md-group-add-on">
                <span class="md-add-on-file">
                    <button class="btn btn-success waves-effect waves-light">Foto</button>
                </span>
            <div class="md-input-file">
                <input type="file" id="submit" name="FotoCapa" class=""/>
                <input type="text" class="md-form-control md-form-file">
                <label class="md-label-file"></label>
            </div>
        </div>
              <div id="success"></div>
          </form>
      </div>
      <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Alterar</button>
        <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>
      </div>
    </div>
  </div>
</div>

With Jquery, I’m doing it this way:

<script type="text/javascript">
 $(function(){
    $('#submit').click(function(e) {
      e.preventDefault();
      var formData = new FormData();
      formData.append('image', $('#fotoCapa').prop('files')[0]);
      $.ajax({
          url: 'alterar-foto-capa.php',
          data: formData,
          type: 'post',
          success: function(response){
             console.log(response);
              if(response){    
                 $('#success').html("<div class='alert alert-success'>A foto foi alterada com sucesso!</div>");
                  $('#fotoCapa').val('');
              }else{
                $('#success').html("<div class='alert alert-danger'>" + response + "</div>");
             }
          },
          processData: false,
          cache: false,
          contentType: false
      });
   });        
});          
</script>

The problem is that when I try to get the value with PHP:

$foto = $_FILES["FotoCapa"]['name'];
echo json_encode($foto);

In the console appears the following error:

(index):596 Uncaught TypeError: Cannot read property '0' of undefined
    at HTMLButtonElement.<anonymous> ((index):596)
    at HTMLButtonElement.dispatch (jquery-3.1.1.min.js:3)
    at HTMLButtonElement.q.handle (jquery-3.1.1.min.js:3)

When I change that line:

formData.append('image', $('#fotoCapa').prop('files'));

The console returns null.

  • The right thing wouldn’t be $foto = $_FILES['image']['name'];?

  • Hello Ricardo. Actually the "Fotocapa" is the name of the field, with this $_FILES["FotoCapa"]['name'] is correct. The problem is in Jquery itself.

  • maybe set the properties contentType: false and processData: false on the call Ajax solve

  • It will not work, the id is not fotoCapa. Behold: id="submit" name="FotoCapa"

  • In PHP is also wrong, the name of the field has to be image, or you change at the time of giving the append in Formdata

  • Hello Denis. I made the changes, <input type="file" id="fotoCapa" name="FotoCapa" class=""/>and formData.append('FotoCapa', $('#fotoCapa').prop('files')[0]);, but now returns null.

  • I found the error, you run the function in the event click, the file only exists after the event change

  • By the way Ricardo. You were right about the name of the global variable. It was $foto = $_FILES['image']['name']; as you said. I’m sorry about that ;)

Show 3 more comments

1 answer

1


The error is at the time you invoke the function, if you call it in the event click, the file doesn’t exist yet, so much so that the browser’s file selection window doesn’t even open, you have to call it in the event change, when the window has already been opened and the file has been selected by the user.

Your code with the changes:

$(function(){
    $('#submit').change(function(e) {
      e.preventDefault();
      alert($('#submit').prop('files')[0].name)
      var formData = new FormData();
      formData.append('image', $('#submit').prop('files')[0]);
      $.ajax({
          url: 'alterar-foto-capa.php',
          data: formData,
          type: 'post',
          success: function(response){
             console.log(response);
              if(response){    
                 $('#success').html("<div class='alert alert-success'>A foto foi alterada com sucesso!</div>");
                  $('#fotoCapa').val('');
              }else{
                $('#success').html("<div class='alert alert-danger'>" + response + "</div>");
             }
          },
          processData: false,
          cache: false,
          contentType: false
      });
   });        
});          
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header btn-primary">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">ALTERAR FOTO</h4>
      </div>
      <div class="modal-body">
          <form method="post" id="form-upload" novalidate enctype="multipart/form-data">
               <label for="email">Tamanho da imagem: 1170 x 300</label>
               <div class="md-group-add-on">
                <span class="md-add-on-file">
                    <button class="btn btn-success waves-effect waves-light">Foto</button>
                </span>
            <div class="md-input-file">
                <input type="file" id="submit" name="FotoCapa" class=""/>
                <input type="text" class="md-form-control md-form-file">
                <label class="md-label-file"></label>
            </div>
        </div>
              <div id="success"></div>
          </form>
      </div>
      <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Alterar</button>
        <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>
      </div>
    </div>
  </div>
</div>
When rescuing via PHP, you will need to use the same name you used in formData.append()

  • 1

    Bingo Denis. It worked perfectly. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.