2

I have a modal form using bootstrap. The form contains some text inputs and a image input.

I submit the form with ajax, and all data is received at the PHP file correctly. Alas, the image isn't being uploaded.

What is my code problem?

<script>
    $(document).ready(function () {
        $("input#submit").click(function(){
            $.ajax({
                type: "POST",
                url: "insert.php", 
                data: $('form.contact').serialize(),             
                success: function(msg){
                    $("#th").html(msg)                 
                    $("#form-content").modal('hide');  
                    $("#pro").html(content);
                },
                error: function(){
                    alert("failure");
                }
            });
        });
    });
</script>

The form:

 <form class="contact" name="contact" enctype="multipart/form-data">

      <label for="inputNombre" class="sr-only">Título</label>
      <input id="inputNombre" name="inputNombre" class="form-control" placeholder="Título" required="TRUE" autofocus="" type="text">
      <br> 
       ....
      <div class="upload_pic1 inline">
           <input id="imagen" name="imagen" type="file">
      </div>
 <div class="modal-footer">
    <a href="#" class="btn" data-dismiss="modal">Cerrar</a>
    <input id="submit" class="btn btn-success" type="submit" value="Crear">
    </div>
    </div>

    </form>

EDIT:

insert.php

 <?php

session_start();
if (!isset($_SESSION["name"]) && $_SESSION["name"] == "") {
    // user already logged in the site
    header("location: Login.html");
}  

require_once('funt.php');
conectar('localhost', 'root', '', 'db');

if (isset($_POST['inputNombre'])) {
    $nombre = strip_tags($_POST['inputNombre']);
    ....
    //Here the var imagen     
    if(is_uploaded_file($_FILES['imagen']['tmp_name'])){
        $rutaEnServidor='imagenes';
        $rutaTemporal=$_FILES['imagen']['tmp_name'];
        $nombreImagen=$_FILES['imagen']['name'];
        $rutaDestino=$rutaEnServidor.'/'.$nombreImagen;
        move_uploaded_file($rutaTemporal,$rutaDestino);
    } else {   //Always enter here, so is not uploaded
         $rutaEnServidor='imagenes';
         $rutaTemporal='/noPicture.png';
         $rutaDestino=$rutaEnServidor.'/noPicture.png';
         move_uploaded_file($rutaTemporal,$rutaDestino);
     }
 ...

How can I change this and upload the picture with all data in form?

Ryan Vincent
  • 4,483
  • 7
  • 22
  • 31
user3745888
  • 6,143
  • 15
  • 48
  • 97

1 Answers1

0

You can use FormData interface. Then you have to tell jQuery not to set content type, nor process data.

Check compatibility table for the FormData constructor first. It might suffice.

Otherwise read through this discussion, How can I upload files asynchronously?.

Community
  • 1
  • 1
Luka Žitnik
  • 1,160
  • 8
  • 15