Upload Ajax and PHP

-1

I'm trying to upload images via AJAX and PHP, but to no avail. I've reviewed, updated, anyway, codes hit all the other codes I searched, I really do not 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 that of the photo:

    
asked by anonymous 26.06.2018 / 01:27

1 answer

2

FormData only supports <form> in builder .

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

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

Or, you can use append.

var theFile = $(this)[0].files[0];
var fileName = theFile.name;
var formData = new FormData();
formData.append(fileName, theFile);
    
26.06.2018 / 02:13