Ajax and PHP for image upload + information registration

Asked

Viewed 524 times

3

I am hitting myself since yesterday with an upload of images in AJAX. I will publish the advances I have studied and the difficulties I still have in case anyone can help me :)

My script as I always did (no pictures) was basically the form

<form id="cadastrar-evento" method="POST" enctype="multipart/form-data">

    <label>Título</label>
    <input class="form-control" type="text" placeholder="Título do Evento" name="titulo">

    <label>Descrição</label>
    <textarea class="form-control" type="text" placeholder="Descrição do Evento" name="descricao" id="descricao-evento" maxlength="240"></textarea>

    <hr>

    <label>Fotos</label>

    <input id="selecao-arquivo1" type="file" name="imagem1">
    <input id="selecao-arquivo2" type="file" name="imagem2">
    <input id="selecao-arquivo3" type="file" name="imagem3">

    <input type="submit" class="btn btn-success" value="Cadastrar Evento" id="botao">

Meu Ajax

//Cadastrar
$('form#cadastrar-evento').submit(function(e){
    e.preventDefault();

    var form = $(this);

    //(...) Validações

    var valores = form.serialize();

    $.ajax({
        type : 'POST',
        url : 'dados/cadastro-evento.php',
        data : valores,
        dataType : 'json',
        success : function(data){
            if(data.status == 1){
                alert(data.msg);
                window.location.href="index.php?pg=eventos";
            }else{
                alert(data.msg);
            }
        }
    });
});

But then, researching, I checked I needed to replace the serialize by the formData method and I did this:

//Cadastrar
$('form#cadastrar-evento').submit(function(e){
   e.preventDefault();

   var form = $(this);

   //(...) Validações

   valores = new FormData(form);
    //var valores = form.serialize();

    $.ajax({
        type: 'POST',
        url: 'dados/cadastro-evento.php',
        data: valores,
        contentType: false,
        cache: false,
        processData:false, 
        dataType: 'json',
        success: function(data){
            if(data.status == 1){
                alert(data.msg);
                window.location.href="index.php?pg=eventos";
            }else{
                alert(data.msg);
            }
        }
    });
});

But my console presents as if the formData had not set?

inserir a descrição da imagem aqui

In PHP I return a json, but from what I understand also I can’t use the return this way anymore. Or I can?

if($sqlInsereEvento){
    $retorno = array("status" => 1, "msg" => "Evento cadastrado com sucesso!");
    echo json_encode($retorno);
    exit;
}else{
    $retorno = array("status" => 0, "msg" => "Ocorreu algum erro ao cadastrar este evento, tente novamente.");
    echo json_encode($retorno);
    exit;
}

Thank you in advance if anyone can clarify these doubts.

UPDATE

Now no errors appear in JS, this is my latest version:

    (...)
    valores = new FormData(form);
    //var valores = form.serialize();

    $.ajax({
        type: 'POST',
        url: 'dados/cadastro-evento.php',
        data: {valores},
        contentType: false,
        cache: false,
        processData:false, 
        dataType : 'json', //Sem o JSON não recebo retorno do PHP. Recebo Undefined.
        success : function(data){
            if(data.status == 1){
                alert(data.msg);
                window.location.href="index.php?pg=eventos";
            }else{
                alert(data.msg);
            }
        }
    });

But apparently values do not arrive in my PHP. I tried to print the posts and it just returns me "hi" on Alert.

//(...)

$titulo      = mysqli_real_escape_string($conn, $_POST['titulo']);
$descricao   = mysqli_real_escape_string($conn, $_POST['descricao']);

//Verifica Campos Vazios caso js esteja com problemas
if(empty($titulo) || empty($descricao)){
    $retorno = array("status" => 0, "msg" => "oi $titulo $descricao");
    echo json_encode($retorno);
    exit;
}
  • I believe your problem is that in the ajax post, you say you are sending a data json, and it is not, remove the datatype

  • From a look here https://answall.com/questions/9704/fazer-upload-archive-com-ajax

  • @Andersonhenrique then my PHP returns "Undefined" to Ajax and falls into that last problem I mentioned there. I’m not sure how to return pro js errors :/

  • @Andersonhenrique Oh yes, I have seen this issue. But I still have difficulty implementing. In this file there he considers only sending image (from what I understand)

  • tries like this: date:{values}

  • @Jorgematheus Hummm, stopped returning error on the console. Now js features an empty Alert. I’ll run some tests on my PHP and confirm. But I may have solved :)

  • So you have to send an object on the date, so you have to have the {}. If so, I reply and you mark as correct.

  • @Aryanavalcanaia I believe the problem is in php, come on, follow the steps, indicate the position of the new Form, I know you’re taking the event by id but just as a precaution, data = new Form($('form#register-event')[0]), remove the datatype: json, so that ajax uses the correct method automatically, and if you can edit and put your php receiving the post

  • @Andersonhenrique I think the js same :/

  • @Jorgematheus the problem is in ajax that it does not send the PHP pro instructions. if I redo ajax using serialize() it passes all the instructions (except $_FILES)

Show 5 more comments

1 answer

1


I adjusted the js and solved :)

HTML

<form id="cadastrar-evento" method="POST" enctype="multipart/form-data">

   <label>Título</label>
   <input class="form-control" type="text" placeholder="Título do Evento" name="titulo">

   <label>Descrição</label>
   <textarea class="form-control" type="text" placeholder="Descrição do Evento" name="descricao" id="descricao-evento" maxlength="240"></textarea>

   <hr>

   <label>Fotos</label>

   <input id="selecao-arquivo1" type="file" name="imagem1">
   <input id="selecao-arquivo2" type="file" name="imagem2">
   <input id="selecao-arquivo3" type="file" name="imagem3">

   <input type="submit" class="btn btn-success" value="Cadastrar Evento" id="botao">

</form>

Ajax

$("form#cadastrar-evento").submit(function(e) {
    e.preventDefault();

    var data = new FormData(this);

    $.ajax({
        url: "dados/cadastro-evento.php",
        type: "POST",
        data: data,
        mimeType: "multipart/form-data",
        dataType : 'json',
        contentType: false,
        cache: false,
        processData:false,
        success: function (data) {
            alert(data.msg);
        }
    });
});

PHP captures post and files and handles normal according to what I want

//Textos
$titulo      = $_POST['titulo'];
$descricao   = $_POST['descricao'];

//Imagens
$imagem1     = $_FILES['imagem1']['name'];
$imagem2     = $_FILES['imagem2']['name'];
$imagem3     = $_FILES['imagem3']['name'];

//Exemplo de retorno
//Verifica Campos Vazios caso js esteja com problemas
if(empty($titulo) || empty($descricao)){
    $retorno = array("status" => 0, "msg" => "Você precisa preencher os campos obrigatórios.");
    echo json_encode($retorno);
    exit;
}
  • 1

    put the full answer!!

  • @Leocaracciolo I thought that together with the statement had become clear. Answer edited.

  • So your answer got better to understand!!

Browser other questions tagged

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