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?
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
– Anderson Henrique
From a look here https://answall.com/questions/9704/fazer-upload-archive-com-ajax
– Anderson Henrique
@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 :/
– Aryana Valcanaia
@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)
– Aryana Valcanaia
tries like this: date:{values}
– Jorge.M
@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 :)
– Aryana Valcanaia
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.
– Jorge.M
@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
– Anderson Henrique
@Andersonhenrique I think the js same :/
– Aryana Valcanaia
@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)
– Aryana Valcanaia