Save image in a server folder and save the path in MySQL with PHP and AJAX

1

I try to save an image in a server folder and then save the path in my DB to later show it in a html table.

I'm working with MySQL , PHP and AJAX . I have seen several ways to do it on the web but I have not been able to solve it.

I get an error in the new category file in the insert.

This is the code registration_categories.php:

<?php
    if (isset($con))
    {
?>
<!-- Modal -->
<div class="modal fade" id="nuevoCliente" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel"><i class='glyphicon glyphicon-edit'></i> Agregar nuevo catalogo</h4>
      </div>
      <div class="modal-body">
      <form class="form-horizontal" method="post" id="guardar_categoria" name="guardar_categoria" enctype="multipart/form-data">
        <div id="resultados_ajax"></div>

         <div class="form-group">
            <label for="foto" class="col-sm-3 control-label">Foto</label>
            <div class="col-sm-8">
              <input type="file" class="form-control" id="foto" name="foto">
            </div>
          </div>

          <div class="form-group">
            <label for="nombre" class="col-sm-3 control-label">Nombre</label>
            <div class="col-sm-8">
              <input type="text" class="form-control" id="nombre" name="nombre" required>
            </div>
          </div>


          <div class="form-group">
            <label for="descripcion" class="col-sm-3 control-label">Descripción</label>
            <div class="col-sm-8">
                <textarea class="form-control" id="descripcion" name="descripcion"   maxlength="255" ></textarea>

            </div>
          </div>             

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
        <button type="submit" class="btn btn-primary" id="guardar_datos">Guardar datos</button>
      </div>
      </form>
    </div>
  </div>
</div>
<?php
    }
?>

The file where you run the ajax: categories.js

    $(document).ready(function(){
            load(1);
        });

        function load(page){
            var q= $("#q").val();
            $("#loader").fadeIn('slow');
            $.ajax({
                url:'./ajax/buscar_categorias.php?action=ajax&page='+page+'&q='+q,
                 beforeSend: function(objeto){
                 $('#loader').html('<img src="./img/ajax-loader.gif"> Cargando...');
              },
                success:function(data){
                    $(".outer_div").html(data).fadeIn('slow');
                    $('#loader').html('');

                }
            })
        }



    function eliminar (id)
        {
        var q= $("#q").val();
        if (confirm("Realmente deseas eliminar la categoría")){ 
        $.ajax({
        type: "GET",
        url: "./ajax/buscar_categorias.php",
        data: "id="+id,"q":q,
         beforeSend: function(objeto){
            $("#resultados").html("Mensaje: Cargando...");
          },
        success: function(datos){
        $("#resultados").html(datos);
        load(1);
        }
            });
        }
        }



$( "#guardar_categoria" ).submit(function(event){
$('#guardar_datos').attr("disabled", true); 

    var datos = new FormData($("#guardar_categoria")[0])
    $("resultados_ajax").html("Mensaje: Cargando...")
    $.ajax({
        url: 'ajax/nueva_categoria.php',
        type: 'POST',
        data: datos,
        contentType: false,
        processData: false,
        success: function(datos){
            $("#resultados_ajax").html(datos);
            $('#guardar_datos').attr("disabled", false);
            load(1);
        }
    });
    event.preventDefault()
})



$( "#editar_categoria" ).submit(function( event ) {
  $('#actualizar_datos').attr("disabled", true);

 var parametros = $(this).serialize();
     $.ajax({
            type: "POST",
            url: "ajax/editar_categoria.php",
            form-data: parametros,
             beforeSend: function(objeto){
                $("#resultados_ajax2").html("Mensaje: Cargando...");
              },
            success: function(datos){
            $("#resultados_ajax2").html(datos);
            $('#actualizar_datos').attr("disabled", false);
            load(1);
          }
    });
  event.preventDefault();
})


    $('#myModal2').on('show.bs.modal', function (event) {
      var button = $(event.relatedTarget) // Button that triggered the modal
      var button = button.data('foto')
      var nombre = button.data('nombre') 
      var descripcion = button.data('descripcion') 
      var id = button.data('id') 
      var modal = $(this)
      modal.find('.modal-body #mod_foto').val(foto)
      modal.find('.modal-body #mod_nombre').val(nombre)
      modal.find('.modal-body #mod_descripcion').val(descripcion) 
      modal.find('.modal-body #mod_id').val(id)
    })

And the file that receives the ajax and that saves the image and the path in the bd: new_categoria.php

<?php
include('is_logged.php');//Archivo verifica que el usario que intenta acceder a la URL esta logueado
/*Inicia validacion del lado del servidor*/

if(empty($_POST['nombre'])) {
       $errors[] = "Nombre vacío";  
    } else if (!empty($_POST['nombre'])){
    /* Connect To Database*/
    require_once ("../config/db.php");//Contiene las variables de configuracion para conectar a la base de datos
    require_once ("../config/conexion.php");//Contiene funcion que conecta a la base de datos
    // escaping, additionally removing everything that could be (html/javascript-) code


    $nombre=mysqli_real_escape_string($con,(strip_tags($_POST["nombre"],ENT_QUOTES)));
    $descripcion=mysqli_real_escape_string($con,(strip_tags($_POST["descripcion"],ENT_QUOTES)));                  
    $date_added=date("Y-m-d H:i:s");
    $foto=isset($_FILES["foto"]);
        if ($foto["type"] == "img/jpg" OR $foto["type"] == "img/jpeg" ) {
            $ruta = "../img".md5($foto["tmp_name"]).".jpg";   

    $sql="INSERT INTO categorias (nombre_categoria, descripcion_categoria,date_added) VALUES ('$ruta','$nombre','$descripcion','$date_added')";
    $query_new_insert = mysqli_query($con,$sql);
        if ($query_new_insert){
            move_uploaded_file($tmp_name, $ruta);
            echo "El catalogo ha sido ingresada satisfactoriamente.";
        } else{
            $errors []= "Lo siento algo ha salido mal intenta nuevamente.".mysqli_error($con);
        }
    } else {
        $errors []= "Error desconocido.";
    }
    }


    if (isset($errors)){

        ?>
        <div class="alert alert-danger" role="alert">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
                <strong>Error!</strong> 
                <?php
                    foreach ($errors as $error) {
                            echo $error;
                        }

                    ?>
        </div>
        <?php
        }
        if (isset($messages)){

            ?>
            <div class="alert alert-success" role="alert">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    <strong>¡Bien hecho!</strong>
                    <?php
                        foreach ($messages as $message) {
                                echo $message;
                            }
                        ?>
            </div>
            <?php
        }
  ?>
    
asked by Jeinner Marulanda 26.07.2017 в 04:48
source

1 answer

1

When you need to record an image by ajax within a form, you need to do it by formdata this calls everything that contains the formdata variable within the form ... if you use data: "id="+id,"q":q, it will only take the plain text and the images will not go inside it

First you generate a variable within the function submit that contains the entire form:

var formData = new FormData($(this)[0]);

Then you call it so that it sends by means of the variable all the info of the form data:formData, ... so you in the file that inserts the data in the database you can choose that data are what will be saved

Here I leave a functional ajax that sends the image file to the file that records to the base.

    $("#prod_n").submit(function(){
        if($('#nombreProd').val()!= ""){
            if(!this.checkValidity || this.checkValidity()){
                var formData = new FormData($(this)[0]);
                event.preventDefault();
                $.ajax({
                    type:"POST",
                    url:"partes/productos/include/prod_n.php?ts=" + new Date().getTime(),
                    data:formData,
                    beforeSend:function(){
                        $("#np").show();
                        $("#pn").empty();
                        $('#submit').attr("disabled", true);
                    },
                    success:function(response){
                        $("#np").hide();
                        $("#pn").append(response);
                        $('#submit').attr("disabled", false);
                    },
                    async: true,
                    cache: false,
                    contentType: false,
                    processData: false
                })
                return false;
            }
        }
    });
    
answered by 26.07.2017 в 16:56