Upload Ajax and PHP

Asked

Viewed 489 times

-1

I am trying to upload images via AJAX and PHP, but without success. Already reviewed, updated, anyway, the codes match all the other codes I researched, I really don’t understand.

HTML:

<form class="photo_change" method="post" enctype="multipart/form-data">
                <input class="arquivo" name="img" type="file" />
                <input type="submit" class="img_envia" name="envia_img" value="SELECIONAR IMAGEM" />
                <img style="display: none; width:22px; height: 22px; margin-left:10px;" src="/img/loader.gif" /> </form>

Jquery:

$('.img_envia').click(function(){
                    $('.arquivo').trigger('click');
                    return false;
});
 
                $('.arquivo').change(function() {
                  var fileName = $(this)[0].files[0].name;
                  var formData = new FormData($('.photo_change'));
                  $('#modal_photo_content form img').show();
 
                      $.ajax({
                        url:'http://localhost/photo_change.php',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(data){
                            console.log(data);
                            $('.img_envia').removeAttr('disabled','disabled');
                        },
                        error: function() {
                            $('.img_envia').removeAttr('disabled','disabled');
                            alert("ERRO: Tente novamente mais tarde.");
                        }
                      });
 
                });

And in PHP I’m giving a var_dump in the $_FILES variable and $_POST to see if I’m getting something, but the return is always the photo: console log

1 answer

2


The FormData supports only the <form> in the builder.

If the .photo_change is the form, I think you can make, note that has the [0] since the FormData expects the HTML element and not the jQuery object.

var formData = new FormData($('.photo_change')[0]);

Or, you can use the append.

var theFile = $(this)[0].files[0];
var fileName = theFile.name;
var formData = new FormData();
formData.append(fileName, theFile);
  • 1

    Thank you. Very objective. ) I prefer the first way, since validation in PHP is easier.

  • 1

    var formData = new Formdata($('.photo_change').get(0); This option also does the same thing.

Browser other questions tagged

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