POST image, via ajax

0

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

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 grab the onClick or onChange event from "#button_photo" and get the photo and send it via ajax to the controller, then upload it with $ _FILES and return the photo link in ajax to then give an append in the post with the image thumbnail as well,

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

    
asked by anonymous 14.02.2018 / 20:28

1 answer

0

2 things to do

1st add enctype no form

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

2nd 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>
    
14.02.2018 / 20:42