Upload Files with Php and Ajax

1

I am new with Ajax I try to upload files to my folder and store the path in my MySQL, these are my advances:

I have my modal window, with which you place the data of the file:

<form class="form-horizontal" action="../../phpcrud/create_documentos.php" method="POST" id="create_documentos_form" enctype="multipart/form-data">
<div class="modal-body">


  <div class="form-group">
    <label for="titulo" class="col-sm-2 control-label">Titulo</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="titulo" name="titulo" placeholder="Titulo">
    </div>
  </div>

<div class="form-group">
  <label for="archivo" class="col-sm-2 control-label">Elejir Documento</label>
  <div class="col-sm-10">
    <input type="file" name="archivo" id="archivo"/>
  </div>
</div>
</div>

<div class="modal-footer">   
  <button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>
</div>
</div>
</div>

My event is called create_documentos_form, and this is the code of mi.js

$("#create_documentos_modal").on('click', function() {
    $("#create_documentos_form")[0].reset();
    $(".form-group").removeClass('has-error').removeClass('has-success');
    $(".text-danger").remove();
    $(".message_create_documentos").html("");

    $("#create_documentos_form").unbind('submit').bind('submit', function()            
  {
        $(".text-danger").remove();
        var form = $(this);

        var titulo = $("#titulo").val();
        var file2 = document.getElementById("archivo");   //TENGO DUDA
        var archivo = file2.files[0];                     //TENGO DUDA

        if(titulo && archivo) 
        {
            $.ajax({
                url : form.attr('action'),
                type : form.attr('method'),
                data : form.serialize(),
                dataType : 'json',
            });
        }
        return false;
    });
});

I check that my file variable contains something with a console.log ()

Apparently there everything is fine is the name of the image, size etc, I try to store it in my Php file as follows:

 if($_POST) {
 $validator = array('success' => false, 'message_create_documentos' => array());

$titulo = $_POST['titulo'];

$nombre = $_FILES['archivo']['name'];
$tipo = $_FILES['archivo']['type'];
$tamanio = $_FILES['archivo']['size'];
$ruta = $_FILES['archivo']['tmp_name'];
$destino = "archivos/" . $nombre;

$sql = "INSERT INTO documentos (titulo,ruta) VALUES ('$titulo', '$destino')";
$query = $connect->query($sql);

if($query === TRUE) {
    $validator['success'] = true;
    $validator['message_create_documentos'] = "Agregado Exitosamente";
} else {
    $validator['success'] = false;
    $validator['message_create_documentos'] = "Error mientras agrega la información";
 }

$connect->close();
echo json_encode($validator);
}

This part is where the record is lost

    
asked by Rastalovely 14.03.2017 в 20:06
source

4 answers

1
$("#create_documentos_form").unbind('submit').bind('submit', function(){
    $(".text-danger").remove();
    var form = $(this);

    var titulo = $("#titulo").val();
    var file2 = $('#archivo');   //Ya que utilizas jquery aprovechalo...
    var archivo = file2[0].files;       //el array pertenece al elemento

    if(titulo && archivo) 
    {

        // Crea un formData y lo envías
        var formData = new formData(form);
        formData.append('titulo',titulo);
        formData.append('archivo[]',archivo);

        jQuery.ajax({
            url: 'url.php',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
                alert(data);
            }
        });
    }
    return false;
});
    
answered by 14.03.2017 / 21:10
source
0
$.ajax({
        type: "POST",
        url:  "HTML/docAjax.php",
                    data: {
                       post1 = "Post1",
                       post2 = "Post2"                            

                     },
        dataType: "text",
        success: function (data) {

                    //aqui cachas lo que regresas con el archivo php
                   console.log(data);


                }

    });
    
answered by 14.03.2017 в 20:20
0

One solution is to use the API FormData ( IE10+ ).

Example:

$("#create_documentos_form").unbind('submit').bind('submit', function() {
    $(".text-danger").remove();
    var form = $(this);

    var titulo = $("#titulo").val();
    var file2 = document.getElementById("archivo");
    var archivo = file2.files[0];

    if(titulo && archivo) {

        $.ajax({
          url : form.attr('action'),
          type : form.attr('method'),
          data : new FormData(form[0]), // <-- usamos 'FormData'
          dataType : 'json',
          processData: false,  // <-- le indicamos a jQuery que no procese el 'data'
          contentType: false // <-- le indicamos a jQuery no establecer el 'contentType'
        });
    }
    return false;
});
    
answered by 15.03.2017 в 13:38
0

Good morning, permission and to add what I'm showing the percentage on a div? In other words, as you upload the file, show the percentage of upload and you can show that percentage value in a div that has id="percentage" and in a div that has id="progress" style="width: percentage to show;"

I do not know if I made myself understood.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container navbar">
        <h2>Subir Archivos de publicaciones</h2>
        <p>The .active class animates the progress bar:</p>
        <div class="form collapse navbar-collapse">

            <form action="" id="form-subirimg">
                <div class="form-group">
                    <label class="control-label" for="cod"><span class="glyphicon glyphicon-user"></span> Codigo de registro</label>
                    <input type="file" class="form-control" name="file" id="subir" multiple required placeholder="Ingrese codigo para registrar">
                </div>

                <div class="progress">
                    <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" id="progress" style="min-width: 5%;">
                        <div id="porcentaje"></div>
                    </div>
                </div>

                <div class="form-group" id="msm">

                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-floppy-save"></span>Subir</button>
                    <button type="button" class="btn btn-danger btn-default pull-rigth" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
                </div>
            </form>

        </div>

    </div>
 <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<script src="https://code.jquery.com/jquery-migrate-3.0.1.js"></script>
    
answered by 13.12.2017 в 04:18