Ajax upload does not send image or parameter

1

I'm trying to upload without From, for image upload, but I can not.

html

<input id="avatar" type="file" name="avatar" />
<button id="btnOcorrenciaSalvar">Salvar</button>

Javascript code:

$("#btnOcorrenciaSalvar").click(function() {


                event.preventDefault();
                var form_data = new FormData();
                nomeFoto = event.filename;

                var file_data = $("#avatar").prop("files")[0];

                form_data.append("file", file_data)
                form_data.append("foto", nomeFoto)


                $.ajax({
                  url: 'http://url.com.br/temp.php',
                  type: 'POST',
                  data: form_data,
                  async: false,
                  cache: false,
                  contentType: false,
                  processData: false,
                  success: function (returndata) {
                      //$("#productFormOutput").html(returndata);
                      alert(form_data);
                  },
                  error: function () {
                      alert("error in ajax form submission");
                  }
                });

                return false;


            });

PHP code to receive POST:

<?php 
    move_uploaded_file($_FILES["avatar"]["tmp_name"], "ocorrencias/" . $_POST["foto"]);
?>
    
asked by anonymous 20.12.2015 / 02:02

3 answers

0

If you used a form would be a lot simpler:

<form id="formulario" method="post" enctype="multipart/form-data" action="upload.php">
  <input type="file" id="imagem" name="imagem" />

</form>

js

$(document).ready(function () {
    /* #imagem é o id do input, ao alterar o conteudo do input execurará a função baixo */
    $('#imagem').live('change', function () {
        $('#visualizar').html('<img src="ajax-loader.gif" alt="Enviando..."/> Enviando...'); /* Efetua o Upload sem dar refresh na pagina */
        $('#formulario').ajaxForm({target: '#visualizar' /* o callback será no elemento com o id #visualizar */}).submit();
    });
});
    
20.12.2015 / 06:14
0

The error Uncaught TypeError: undefined is not a function , is because the plugin ajaxForm was used, and you did not import it.

If you want to continue using jQuery without plugins, put a: var_dump($_FILES); To understand what is actually being sent by your javascript.

    
21.12.2015 / 14:22
0

I think it's because you forgot to declare the event parameter of the click () function, eg:

$ ("# btnSaveSave"). click (function ( event ) {

and you called it without it: event.preventDefault ();

    
06.04.2018 / 21:18