How to upload an image using jquery/ajax?

Asked

Viewed 3,994 times

3

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 don’t know how to pass the picture data.

How do I inform php that there is an upload?

1 answer

6


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

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

This way it will create a key value structure with the value of the key equal to the name of their <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 show a preview of 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);
}
  • How PHP receives image information?

  • It will receive the image in the super global $_FILES. From there you can change the name of the file, save it in the sufficiency of your server as well as many other things. if you want to read more about this super global you can access this link http://php.net/manual/en/reserved.variables.files.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.