Ajax upload does not send image and parameter

Asked

Viewed 190 times

1

I’m trying to upload without From, for image upload, but I can’t.

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 the POST:

<?php 
    move_uploaded_file($_FILES["avatar"]["tmp_name"], "ocorrencias/" . $_POST["foto"]);
?>

3 answers

0

The mistake Uncaught TypeError: undefined is not a function, is why the plugin was used ajaxForm, and you didn’t care about him.

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

0

If you used a form it would be much 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();
    });
});
  • Good morning. This error appears Uncaught TypeError: undefined is not a function . on the line where the $('#formulario').ajaxForm. What is this?

  • in place of #form should be the id of your form!

0

I believe it is because you forgot to declare the Event parameter of the click() function, e.g.:

$("#btnOcorrenciaSalvar"). click(Function(Event) {

and you called without him: Event.preventDefault();

Browser other questions tagged

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