How to upload image using ajax and PHP?

1

I'm trying to upload images with AJAX and PHP, but I'm not successful and can not find the error.

My code is:

$('.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) {
      alert(data);
    },
    error: function() {
      alert("ERRO: Tente novamente mais tarde.");
    }
  });
});
<form action="" 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" />
</form>

And PHP

<?php
session_start();
if(isset($_FILES['img'])){
    require('connection.php');
    $id = $_SESSION['login_id'];
    $extensoes = array('png','jpg','jpeg');
    $busca_dados_user = mysqli_query($conexao,"SELECT * FROM users WHERE id = '$id'");
    if(mysqli_num_rows($busca_dados_user) == 1){

    }


}else{
    echo "Erro [003]: Faltam dados para a requisição.";
}
?>

But always returns: Erro [003]: Faltam dados para a requisição.

Is there something missing or wrong?

    
asked by anonymous 25.06.2018 / 00:37

2 answers

1

The file is not being uploaded.

Put the class in the form class="photo_change" and use the object FormData as follows data: new FormData($('.photo_change')[0]),

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><formclass="photo_change" method="POST" enctype="multipart/form-data">
    <input class="arquivo"  name="img" type="file" />
</form>

<div id="result"></div>

<script language="javascript">
$('.arquivo').change(function() {

    $.ajax({
        url: "http://localhost/photo_change.php",
        type: "POST",
        data: new FormData($('.photo_change')[0]),
        mimeType: "multipart/form-data",
        contentType: false,
        processData:false,
        success: function (data) {
            $("#result").html(data);
        }
    });
});
</script>

photo_change.php

<?php
session_start();
if(is_array($_FILES)){
    require('connection.php');
    $infos = $_FILES['img'];
    $id = $_SESSION['login_id'];
    $extensoes = array('png','jpg','jpeg');
    $busca_dados_user = mysqli_query($conexao,"SELECT * FROM users WHERE id = '$id'");
    if(mysqli_num_rows($busca_dados_user) == 1){
        var_dump($infos);
    }


}else{
    echo "Erro [003]: Faltam dados para a requisição.";
}

?>
  

You can also use

data: new FormData(document.getElementById("form1")),

  

and no form with id

<form id="form1" method="POST" enctype="multipart/form-data">

    
25.06.2018 / 03:17
1

Ajax

                  $('.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){
                            alert(data);
                        },

                        xhr: function() {  // Custom XMLHttpRequest
                        var myXhr = $.ajaxSettings.xhr();
                        if (myXhr.upload) { // Avalia se tem suporte a propriedade upload
                        myXhr.upload.addEventListener('progress', function () {
                        /* faz alguma coisa durante o progresso do upload */
                        }, false);
                      }
                        return myXhr;
                     },

                        error: function() {
                            alert("ERRO: Tente novamente mais tarde.");
                        }
                      });
});

PHP

Instead of:

if(isset($_FILES['img'])){

I've changed to:

if (!empty($_FILES['img']['name'])) {
    
25.06.2018 / 01:29