Upload with json+Modal+Javascript

Asked

Viewed 287 times

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. inserir a descrição da imagem aqui

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">&times;</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?

  • and the html page of the <main> tag.. this is the last line of the page

  • php return is ; {"error":"No file!"}

2 answers

1

I managed to solve it this way.

PHP:

<?php
include("../includes/config.php");

    if($_POST){

        //variaveis
        $id         = $_POST['idclienteimg'];
        $acao       = $_POST['acao'];
        $file       = $_FILES['fileI'];
        $numFile    = count(array_filter($file['name']));
        $folder     = '../arquivos/anexos';
        $folderB    = 'arquivos/anexos';

        //REQUISITOS
        $permite    = array('image/jpeg', 'image/png', 'image/bmp');

        //validações
        $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){
             echo "Return Code: " . 'Nenhum arquivo foi selecionado' . "<br/>";
        } 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){
                            echo "Return Code: " . $errorMsg[$error] . "<br/>";
                        }   else if(!in_array($type, $permite)){                    
                            echo 'Erro: arquivo não suportado(somente arquivos de imagens)!';   
                        }   else if($size > $maxSize) {                 
                            echo 'Erro arquivo ultrapassa o limite de 5MB';                      
                    } else {

                        //grava um log de arquivos inseridos
                        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',$folderB);
                            $rs->bindParam(':id_cliente',$id);
                            $result = $rs->execute();       
                            if ( ! $result ) {
                                    echo 'Erro:' . $result;
                                    exit;
                                }
                                echo 'Upload Realizado com Sucesso!';   

                        } else {
                            echo 'Erro interno do sistema, tente mais tarde!';

                        }
                    }
                }
            }
        }
?>

AJAX:

$("#uploadimage").on('submit',(function(e) {
        e.preventDefault();
        $("#message").empty();
        $('#loading').show();

        $.ajax({
            url: 'estrutura/upaddimg.php',
            type: 'POST',
            data: new FormData(this),
            processData: false,         
            contentType: false,         
            success: function(data) {              
                console.log(data);
                $('#loading').show();
                $("#message").html(data);
                var tt = data;
            }
        });


    }));

0

The problem is that the return of Ajax is coming with information that does not matter to JSON, so the error:

Uncaught Syntaxerror: Unexpected token < in JSON at position...

See that the return of Ajax is returning, in addition to the expected JSON, several HTML codes shown in the question print:

<ul>....

By doing the JSON.parse(xhr.responseText) will result in error because these HTML codes are not part of the expected JSON.

When a request is made via Ajax expecting a JSON, nothing else should come as an answer. Any other character other than JSON will cause an error. Therefore, delete from the page that sends the return of Ajax everything that is not part of the echo json_encode($ret);, like these HTML codes that are returning together.

Then you can say: "I can’t delete HTML because it’s part of the page".

So you have 2 alternatives:

Or isolate HTML code with if{} when there is a Ajax request or creates a file .php just for this (without HTML), which I find the most recommended. As said, the important thing (and what matters) is that the return is only JSON.

Browser other questions tagged

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