problem when uploading photo with jquery and php

0

At this moment I am trying to upload a photo with ax folder but the photo save is not executed, because when I press the button it is sent the whole page and the process is not done without reloading the page, to then I leave the codes that I have in the localhost. html

<form name="frmSubir" id="frmSubir" method="post" enctype="multipart/form-data">
          <input type="file" name="foto" class="profile-image-upload hidden"/>
          <div style="color:#999;">click en la foto para cambiarla</div>
          <input type="submit" class="btn_enviar" value="Guardar Foto" />
          </form>
        <div id="cargado"></div>

the js

$(document).ready(function(){
$('.btn_enviar').on("click", function(evt){
    evt.preventDefault();
    // declaro la variable formData e instancio el objeto nativo de javascript new FormData
    var formData = new FormData(document.getElementById("frmSubir"));
    // declaro la variable ruta
    var ruta = 'peticion/guardar-foto.php';
    // iniciar el ajax
    $.ajax({
        url: ruta,
        // el metodo para enviar los datos es POST
        type: "POST",
        // colocamos la variable formData para el envio de la imagen
        data: formData,
        contentType: false,
        processData: false,
        beforeSend: function(){
        $('#cargado').prepend('<i class="fa fa-refresh fa-spin"></i> subiendo foto...');
        },
        success: function(data){
        $('#cargado').fadeIn("slow",function(){
                $('#cargado').html(data);
        });
        }
    });
});
});

and the php

<?php
if(isset($_FILES["foto"]))
{
$file = $_FILES["foto"];
$nombre = $file["name"];
$tipo = $file["type"];
$ruta_provisional = $file["tmp_name"];
$size = $file["size"];
$dimensiones = getimagesize($ruta_provisional);

$width = $dimensiones[0];
$height = $dimensiones[1];
$carpeta = "img/foto/";
if($tipo != 'image/jpg' && $tipo !='image/jpeg' && $tipo !='image/png' && $tipo !='image/gif')
{echo '<h3 class="alert alert-danger" role="alert"><i class="fa fa-close"></i> Error: el archivo no es una imagen.</h3>';}
else if ($size > 1024*1024)
{echo '<h3 class="alert alert-danger" role="alert"><i class="fa fa-close"></i> Error: el tamaño máximo es de una 1Mb.</h3>';}
else if ($width > 500 || $height > 500)
{echo '<h3 class="alert alert-danger" role="alert"><i class="fa fa-close"></i> Error la anchura y la altura maxima permitida es 500px</h3>';}
else if($width < 100 || $height < 100)
{echo '<h3 class="alert alert-danger" role="alert"><i class="fa fa-close"></i> Error la anchura y la altura mínima permitida es 100px</h3>';}
else
{
    $src=$_SERVER['DOCUMENT_ROOT'].'/'.$carpeta.$nombre;
    move_uploaded_file($ruta_provisional, $src);
    echo '<h3 class="alert alert-success" role="alert"><i class="fa fa-check"></i> Se actualizó tu foto de perfil.</h3>';
    //echoecho '<meta http-equiv="refresh" content="1" />';
}
}
?>
  

the root document is already there that does not go there hahaha that if I take it out afterwards since it had test on the localhost, thanks for your help I use the jquery 3.2.1

    
asked by Jaime Mateus 01.09.2017 в 04:33
source

3 answers

1

The page is reloaded because you use a submit , it replaces:

<input type="submit" class="btn_enviar" value="Guardar Foto" />

for

<button type="button" class="btn_enviar" value="Guardar Foto" >Guardar Foto</button>
    
answered by 01.09.2017 в 05:11
0

Good morning

The following was an implementation taken from Simple File Uploads Using jQuery & AJAX worked for me:

As appropriate your html "will have"

<input type="file" id="Filedata" name="Filedata" placeholder="[tu leyenda]" 
      accept="image/*" onchange="prepareUpload(event)" />

in my case the accept="image / *" is because I indicate only images; Look at HTML accept Attribute which you can put:

We declare

function prepareUpload(event)
{
  files = event.target.files;
} 

and separately finally how we would process the data to send the file; Of course if you need more parameters add them as appropriate (by GET or POST).

// Previo a tu Ajax
var dataf = new FormData();
$.each(files, function(key, value)
{
    dataf.append(key, value);
});

// el Url que se indica fijate que termina en "?files" es necesario, 
// si fueran más parámetros pos GET te sugiero ponerlo al final "&files"
// aquí es solo uno por eso el "?"
$.ajax( {
    url:"[rutayArchivoqueProcesaraelArchivo]?files",
    cache:false,
    dataType: 'json',
    type: 'POST',
    data: dataf,
    processData: false, 
    contentType: false, 
    success: function (data) {
            // lo que hagas en caso éxito
    },
    error: function (jqXHR, textStatus, errorThrown) {
        // Lo que hagas en caso falle
    }
}
);

I hope it will be useful for you.

  

Notes:

     

Take time to find the code as implemented.

     

Do not use FORM tags any time I get the data with jQuery with your selector   input textarea ... etc both its name and value to pass them through POST or   GET according to definition

    
answered by 01.09.2017 в 05:54
0

So that the page does not recharge you can use the jquery.form library and its function ajaxForm that will realize the submit without reloading the page

add the library to the head:

<script src="http://malsup.github.com/jquery.form.js"></script> 

modify the form by adding the action and removing the% button submit from <form> and replacing it by <button>

<form action="peticion/guardar-foto.php" name="frmSubir" id="frmSubir" method="post" enctype="multipart/form-data">
      <input type="file" name="foto" class="profile-image-upload hidden"/>
      <div style="color:#999;">click en la foto para cambiarla</div>
</form>

<button type="button" class="btn_enviar" value="Guardar Foto" >Guardar Foto</button>

in javascript adds:

$(document).ready(function(){
    $("#frmSubir").ajaxForm({
        dataType: 'json',
        resetForm: true,
        success: function(data) {
            //aqui tu codigo despues de finalizar la carga del "ajax" 
            $('#cargado').fadeIn("slow",function(){
                $('#cargado').html(data);
            });            
        }
    });

    //evento click al boton btn_enviar
    $('.btn_enviar').click(function() {
        $("#frmSubir").submit();        
    });
});
    
answered by 01.09.2017 в 05:49