How to upload an image using jquery / ajax?

0

I am sending the following data to save a form:

function editaFeira(id, descricao){
if (confirm("Confirma a alteração de " + descricao + "?"))
{
  $.ajax({
    type: "POST",
    url: "functions/editarFeira.php",
    data: {id: id,
           descricao: $("#descricao").val(),
           horario: $("#horario").val(),
           pagamento: $("#pagamento").val(),
           quem: $("#quem").val(),
           //QUERO BOTAR A IMAGEM AQUI!!!
          },
    success: function(data) {
      if (data == 'ok'){
        alert(descricao + ' editado com sucesso!');
        listaFeira();
      }
    }
  });
}
}

I can send all the common data, but I do not know how to pass the image data.

How do I tell php that an upload exists?

    
asked by anonymous 20.01.2018 / 15:12

1 answer

1

To send images via AJAX you need to use the object FormData and configure the ajax request in this way. Remember that it is not necessary to get the value separately from each <input> as you are doing, just set an if for your form, something like:

<form id="myForm">
 ...
</form>

In this way it will create a key value structure with the key value equal to name of its <input> .

$.ajax({
    url: 'functions/editarFeira.php',
    method: 'post',
    data: new FormData($('#myForm')[0]),
    cache: false,
    contentType: false,
    processData: false,
    success: function(retorno){

    },
});// Fim do ajax

If you want, you can also preview the image you are loading using the following code:

var input_e = $('#inputImagem')[0]; // input que carrega a imagem
if (input_e.addEventListener) {
    input_e.addEventListener("change", function (evt) {
        var reader = new FileReader();
        var file = this.files[0];
        if (!!file.type.match(/image.*/)) {
            if ( window.FileReader ) {
                reader.onloadend = function (e) {
                    // Muda o src da tag 'img' para mostrar imagem que o usuário carregou
                    $('#image-list').attr('src',e.target.result);
                };
                reader.readAsDataURL(file);
            }
        }
    }, false);
}
    
20.01.2018 / 15:30