How to upload an image using ajax and PHP?

Asked

Viewed 745 times

0

I’m trying to make a upload of images with AJAX and PHP, but I get no success and do 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.

There’s something missing or wrong?

  • A while ago, I was like this same problem. I switched the isset for ! Empty and put a function in Ajax and it worked. I’ll put in the code to see if it helps you.

  • You have to pass a native DOM form object and a jQuery selector always returns an array. Try this: var formData = new Formdata($('. photo_change')[0]);

  • Edited response!!

  • What deja vu! I saw this question there and could not find my answer, but after all it is a different question! https://answall.com/questions/309755/upload-ajax-e-php/309765

  • Then it had already been done! And I waste time answering this one from here. I saw that there are some differences.

2 answers

2


File 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>

<form class="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 in the form with id

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

  • I var_dump $_FILES and ajax returns an empty array. I don’t understand. I don’t think the file is being sent

  • Can you explain why $('. photo_change')[0] and not $('. photo_change') ?

  • 1

    Can, as the reference is the class, and there can be multiple Forms with the same class, the Indice 0 refers to the first form. If this form is the second of your page you should refer to it as Indice 1, i.e. .photo_change')[1]. Already with id is different because it is unique to each element, just do FormData(document.getElementById(idDoForm")

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

In place of:

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

I switched to:

if (!empty($_FILES['img']['name'])) {

Browser other questions tagged

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