undefiened index file

0

I've been stuck with this for several days and I still have not been able to solve it, the thing is that I have a form which I sent with ajax , the form has some fields of type text and one of type file that is my big problem I have tried anyway and I do not want to recognize that input. but if I send the form without ajax that is to say recharging and sending the form directly to the other page if it recognizes the input of type file .

here's what I've tried

    <form action="ajax/info.php" method="post" enctype="multipart/form-data" id="form">
       <input type="text" name="nombre" id="nombre" />
       <input type="text" name="apellido" id="apellido" />
       <input type="text" name="correo" id="correo" />
       <input type="file" name="file" id="file" />

      <button type="submit" id="send" form="form">ENVIAR</button>
   </form>

ajax

       $("#form").submit(function(e){

        var form=$("#form");

         var url="ajax/info.php";

          $.ajax({
                    url: url,
                    method: 'post',
                    data:  form.serialize(),
                    type:"JSON",
                    contentType:"application/json; charset=utf-8"

  }).done(function(res){

         console.log(res)

  }).fail(function(){

         console.log(res)

    })

              e.preventDefautl();
            })
        })

php

  <?php

   $nombre=$_POST["nomre"];
   $apellido=$_POST["apellido"];
   $correo=$_POST["correo"];
   $destino="";
//intente sin if (isset()) tampoco funciono
  if(isset($_FILES["file"])){

      $file=$_FILES["file"]["name"];

       $tmp_name = $_FILES["pictures"]["tmp_name"]
       $destino = "img/" . $_FILES['imagen']['name'];
        move_uploaded_file($tmp_name,$destino);

  }

echo json_encode(array(

                "nombre"=>$nombre,
                "apellido"=>$apellido,
                "correo"=>$correo,
                "file"=>$file
                     ))

?>

in the output I have all the inputs except the file type, it always says undefined index file, but as I mentioned above if I do it directly without ajax if it recognizes it. some help?

    
asked by andy gibbs 19.11.2018 в 17:18
source

1 answer

0

What is happening is that you try to send the file as a text field instead of as what is a data file, you can not use serialize , what you should be FormDAta :

     $("#form").submit(function(e){

        var formData = new FormData(document.getElementById('form'));
         var url="ajax/info.php";

          $.ajax({
                    url: url,
                    type: "POST",
                    data:  formData,
                    dataType: "json"

  }).done(function(res){

         console.log(res)

  }).fail(function(){

         console.log(res)

    })

              e.preventDefautl();
            })
        })

Reference:
Using FormData Objects

    
answered by 19.11.2018 / 17:34
source