POST de imagem, via ajax

Asked

Viewed 804 times

0

hello basically what I want to do is a system similar to the facebook, to create posts. Where you press to send the photo, choose the photo and automatically the photo goes to the server and has a visual feedback that the photo is going and then appears the thumbnail image, my only doubt is how to do the ajax part only in the photo and not in the form Ubmit

VIEW:

<form id="form" action="enviarPost" method="post">
  <div>

    <textarea name="texto"></textarea>

    <input type="file" id="foto" name="foto" style="display: none;">

    <button id="button_foto" type="button"> Enviar Foto</button>

    <button type="submit">Enviar</button>

  </div>
</form>

What I wanted to do was to take the onClick or onChange event from "#button_foto" and take the photo and send it via ajax to the controller, and then upload it with $_FILES and return the link from the photo in ajax, to then append the post with the thumbnail image as well as,

In short: I want to know how to get the input image via ajax and play pro controller.

  • Just replace $("#formulario").submit(function () { for $("#button_foto").click(function () { https://answall.com/questions/9704/fazer-upload-de-arquivo-com-ajax

1 answer

1

2 things to do

1º Add enctype in form

<form enctype="multipart/form-data" id="form" action="enviarPost" method="post">
</form>

2º Add attributes in ajax

$.ajax({
        url: "urldesejada.php",
        data: formData,
        *cache: false,
        contentType: false,
        processData: false,*
        type: "POST",
        success: function(response){}
});

Complete code:

<form enctype="multipart/form-data" id="form" action="enviarPost" method="post">
   <div>
     <textarea name="texto"></textarea>
     <input type="file" id="foto" name="foto" style="display: none;">
     <button id="button_foto" type="button"> Enviar Foto</button>
     <button type="submit">Enviar</button>
   </div>
</form>

<script>
  $(document).ready(function(){

    $('#button_foto').click(function(){

      var imagem = $('button_foto').val();

      $.ajax({
        url: "urldesejada.php",
        data: imagem,
        cache: false,
        contentType: false,
        processData: false,
        type: "POST",
        success: function(response){}
      });

    });

  });
</script>
  • 1

    Whether the data will be sent via AJAX, does not need to have the attribute enctype.

Browser other questions tagged

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