0
Good evening, I need a help, I am uploading multiple files in a modal, but the return of php does not occur as expected.
Calling to MODAL:
$('button.btnaddimg').on('click', function (e) {
e.preventDefault();
var id = document.getElementById('idclienteimg').value;
$('#modalADDIMG').data('id', id).modal('show');
});
Sending files to PHP:
var $formUpload = document.getElementById('formularioimg'),
$preview = document.getElementById('previewimg'),
i = 0;
$formUpload.addEventListener('submit', function(event){
event.preventDefault();
var xhr = new XMLHttpRequest();
var id = $('#modalADDIMG').data('id');
xhr.open("POST", $formUpload.getAttribute('action'));
var formData = new FormData($formUpload);
formData.append("i", i++);
formData.append("id", id);
xhr.send(formData);
xhr.addEventListener('readystatechange', function() {
if (xhr.readyState == 4){
if(xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
/*if (!data.error && data.status == 'ok') {
//$preview.innerHTML += '<br />Enviado!!';
toastr["error"]('Enviado!');
} else {
//$preview.innerHTML = 'Arquivo não enviado';
toastr["error"]('Arquivo não enviado');
}*/
} else {
toastr["error"](xhr.statusText);
}
}
});
HTML Modal form:
<!--Modal: modalADDIMG-->
<div class="modal fade right" id="modalADDIMG" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false">
<div class="modal-dialog modal-side modal-bottom-right modal-notify modal-danger" role="document">
<!--Content-->
<div class="modal-content">
<!--Header-->
<div class="modal-header red">
<p class="heading lead">Adicionar arquivo img/png/jpeg/bmp</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="white-text">×</span>
</button>
</div>
<!--Body-->
<div class="modal-body mb-0 p-0">
<div class="card-body">
<form id="formularioimg" method="post" enctype="multipart/form-data" action="?pg=upaddimg">
<input type="hidden" name="acaoimg" value="IMG">
<input type="hidden" name="idclienteimg" value="<?php echo $id?>">
<div class="file-field">
<div class="d-flex justify-content-center">
<div class="btn btn-danger btn-rounded btn-sm">
<span id="spa">Escolha o arquivo</span>
<input type="file" id="inputArquivo" accept="image/png, image/jpeg" name="img[]" multiple>
</div>
</div>
<center><input class="btn btn-danger btn-rounded btn-sm" id="btnenviaimgcli" type="submit" value="Enviar" /></center>
</div>
<div id="previewimg"></div>
</form>
</div>
</div>
<!--Footer-->
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-outline-danger btn-rounded btn-md ml-4" data-dismiss="modal">Fechar</button>
</div>
</div>
<!--/.Content-->
</div>
</div>
<!--Modal: modalADDIMG-->
PHP:
<?php
include("../includes/config.php");
if($_POST){
$acao = $_POST['acao'];
$id = $_POST['id'];
$file = $_FILES['img'];
$numFile = count(array_filter($file['name']));
//var_dump($numFile);
$folder = 'arquivos/anexos';
//REQUISITOS
$permite = array('image/jpeg', 'image/png', 'image/bmp');
//$permite = array('application/pdf');
$maxSize = 1024 * 1024 * 5;
$errorMsg = array(
1 => 'O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.',
2 => 'O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário HTML',
3 => 'o upload do arquivo foi feito parcialmente',
4 => 'Não foi feito o upload do arquivo'
);
if($numFile <= 0){
$ret = array('error' => 'Sem arquivo!');
//$ret = array('error' => 0);
} else {
for($i = 0; $i < $numFile; $i++){
$name = $file['name'][$i];
$type = $file['type'][$i];
$size = $file['size'][$i];
$error = $file['error'][$i];
$tmp = $file['tmp_name'][$i];
$extensao = @end(explode('.', $name));
$novoNome = rand().".$extensao";
if($error){
$ret = array('error' => $errorMsg[$error]);
//$ret = array('error' => 1);
} else {
file_put_contents('arquivos/post.txt', 'name=' . $novoNome . ',count=' . $numFile . PHP_EOL, FILE_APPEND);
if(move_uploaded_file($tmp, $folder.'/'.$novoNome))
{
$data = date("y-m-d");
$ext = $type;
$sql = "insert into fotos (nomefoto, data, arquivo, tipoarq, path, id_cliente) VALUES (:nomefoto, :data, :arquivo, :tipoarq, :path, :id_cliente)";
$rs = $con->prepare($sql);
$rs->bindParam(':nomefoto',$name);
$rs->bindParam(':data',$data);
$rs->bindParam(':arquivo',$novoNome);
$rs->bindParam(':tipoarq',$ext);
$rs->bindParam(':path',$folder);
$rs->bindParam(':id_cliente',$id);
$result = $rs->execute();
if ( ! $result ) {
$ret = array('error' => $result);
//$ret = array('error' => 2);
}
$ret = array('status' => 'Arquivo insirido com sucesso');
//$ret = array('status' => 3);
} else {
$ret = array('error' => 'Erro interno do sistema, tente mais tarde!');
//$ret = array('error' => 4);
}
}
}
}
//header('Content-Type: application/json');
echo json_encode($ret);
die();
}
?>
Error:
VM16004:3 Uncaught SyntaxError: Unexpected token < in JSON at position 4
at JSON.parse (<anonymous>)
at XMLHttpRequest.<anonymous> (.....min.js:771)
Return of PHP - console.log:
<!--Main layout-->
{"error":"Sem arquivo!"}
What would be this "main layout" of the return of PHP?
– Woss
and the html page of the <main> tag.. this is the last line of the page
– Jefferson Meireles
php return is ; {"error":"No file!"}
– Jefferson Meireles