jQuery AJAX request demo

by amenadiel

HTML

<div class="form">
  <div id="cerrar">X</div>
  <form id="formulario_add" method="POST" enctype="multipart/form-data">
    <h1 align="center">Añadir producto</h1>
    <input type="hidden" id="codigo" name="codigo" value="001">
    <fieldset>
    
    
    <div class="fieldset">


      <div class="descripcion">
        <label for="descrip">Descripción: </label>
        <textarea name="descrip" id="descrip" cols="50" rows="2" placeholder="Escribe la descripción del producto"></textarea>
      </div>
      <div class="precio">
        <label for="precio">Precio: </label>
        <input type="text" name="precio" id="precio" placeholder="Ingrese el precio del producto">
      </div>
      <div class="tallas">
        <label for="tallas">Tallas: </label>
        <input type="text" name="tallas" id="tallas" placeholder="Ingrese las tallas separadas por comas">
      </div>
      <div class="colores">
        <label for="colores">Colores: </label>
        <input type="text" name="colores" id="colores" list="colores_list" placeholder="Ingrese el color que destaque del producto">
        <datalist id="colores_list">

                </datalist>
      </div>
      <div class="imagen">
        <label for="imagen">Imagen: </label>
        <input type="file" name="imagen" id="imagen">
      </div>
      <div class="boton_add">
        <button type="submit" id="btn_add">Agregar producto</button>
      </div>
    </div>
    </fieldset>
  </form>
  <div id="output">
  </div>
</div>

SCSS

#formulario_add {
  display: table;
  table-layout: fixed;
  #output {
    display: block;
    margin-top: 8px;
    padding: 1%;
    border: 1px solid #666;
    background-color: #efefef;
  }
  .fieldset {
    display: flex;
    
    flex-direction: row;
    flex-wrap: wrap;
    &>div {
      padding: 5px;
      flex-basis: 40%;
    flex-grow: 1;
    max-width: 100%;
    &.imagen,
    &.descripcion {
      flex-basis:90%;
    }
      label {
        width: 90px;
        display: inline-block;
      }
    }
  }
}

JavaScript

$(document).ready(() => {
  function addProduct(e) {
    if (e.type == "submit") {
      e.preventDefault();
    }
    var fd = new FormData(this)
    console.log(fd);

    $.ajax({
      url: '/echo/html/',
      type: "POST",
      data: fd,
      processData: false, // tell jQuery not to process the data
      contentType: false, // tell jQuery not to set contentType,
      complete: function(response) {
        $('#output').html(response.responseText);
      },
      error: function() {
        $('#output').html('Bummer: there was an error!');
      },
    });

    return false;
  }


  document.getElementById("formulario_add").addEventListener("submit", addProduct, false);
});