JSON Parse error:

Asked

Viewed 2,775 times

1

I have this error in JSON that I can’t understand.

This is my return on the console:

Syntaxerror: JSON Parse error: Unrecognized token '<'

Who is informed to be on that line:

resultado = JSON.parse(this.responseText);

And this is my piece of code that should receive an image and upload it instead of Thumb:

function transferComplete(evt) {
        resultado = JSON.parse(this.responseText);

        if (resultado.enviado)
        {
            label.attr('class', 'btn btn-warning btn-file');
            $('#thumb_' + resultado.nome).show();
            $('#thumb_old_' + resultado.nome).remove();

            label.attr('data-original-title', resultado.arquivo_antigo).attr('title', resultado.arquivo_antigo).attr('class', 'btn btn-default btn-file');
            label.find('.progress').remove();

        } else
        {
            label.removeClass('upload');
            label.find('.progress').remove();
        }
    }

I hope I have presented my problem clearly to all.

Complete code:

    var arquivos = new Object();
arquivos = {
    gatilho: function () {
        $('label[tipo]').on('drop', function (event) {
            arquivos.handleFileSelect(event, $(this));
        });
        $('label[tipo]').on('dragover', function (event) {
            arquivos.handleDragOver(event);
        });
        $('label[tipo] input').on('change', function (event) {
            arquivos.handleFileSelect(event, $(this));
        });
    },
    handleFileSelect: function (event, id) {

        event.stopPropagation();
        event.preventDefault();
        var label = '';

        function updateProgress(oEvent) {
            if (oEvent.lengthComputable) {
                var percentComplete = (oEvent.loaded / oEvent.total * 100);
                label.find('.percent').css('width', percentComplete + '%');
            }
        }




        // progress on transfers from the server to the client (downloads)

        function transferComplete(evt) {


            resultado = JSON.parse(this.responseText);

            if (resultado.enviado)
            {



               upload.addClass('upload-enviado');
               upload.append('<i class="fa fa-check"></i>');

               label.attr('title', resultado.arquivo_antigo);
               label.find('.progress').remove();
               if (resultado.idItemArq)
                   $('#' + nome).attr('enviado', resultado.idItemArq);
            } else
            {
                label.find('.progress').remove();
            }
        }

        // Create a formdata object and add the files
        var oReq = new XMLHttpRequest();

        oReq.upload.addEventListener("progress", updateProgress, false);
        oReq.addEventListener("load", transferComplete, false);

        var data = new FormData();
        var imagem = '';
        var reader = new FileReader();

        if (event.originalEvent.dataTransfer) {
            var files = event.originalEvent.dataTransfer.files;
            id = id.find('input');
        } else {
            var files = event.target.files;
        }

        arquivo = files[0].name;
        array_arquivo = arquivo.split(".");
        tipo_arquivo = array_arquivo[array_arquivo.length - 1];

        if (files.length > 1) {
            alert('Você deve enviar um arquivo por vez!');
            return 0;
        } else if (files[0].size > 60000000) {
            alert('O arquivo deve ter no máximo 60 Mb');
            return 0;
        } else if (tipo_arquivo == 'cdr' || tipo_arquivo == 'pdf') {
            imagem = "/public/files/thumbs/thumb-" + tipo_arquivo + ".png";
        } else if (tipo_arquivo == 'jpg' || tipo_arquivo == 'jpeg') {
            imagem = "/public/files/thumbs/thumb-jpg.png";
        } else {
            alert('O arquivo deve ser do tipo JPG, CDR ou PDF');
            return 0;
        }
        ;

        nome = id.attr('name');
        upload = $('#upload_' + nome);
        label = upload.find('label');
        data.append(nome, files[0]);
        data.append('idPedido', $('#idPedido').val());
        if (id.attr('enviado'))
            data.append('enviado', id.attr('enviado'));

        upload.find('i').remove();
        label.find('span').remove();
        label.find('img').remove();
        upload.attr('class', 'upload');

        label.append('<div class="progress"><div class="percent"></div></div>');
        label.append('<img class="thumb" id="thumb_' + nome + '" src="' + imagem + '">');

        oReq.open("POST", '/envio/reenvio', true);
        oReq.send(data);
    },
    handleDragOver: function (evt) {
        evt.stopPropagation();
        evt.preventDefault();
        evt.originalEvent.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
    }
}
  • 1

    You can put a console.log(this.responseText) before that line and put in your question the result? Your JSON is in incorrect format and so we can see what the problem is

  • Undefined was the return

  • In addition to formatting your Json, here https://jsonformatter.curiousconcept.com/ validates whether your Json is valid.

  • So it’s because your JSON is not completed

  • Which return JSON in which the PARSE?

  • Can you show the rest of the code that ajax does? which is the address you’re using to fetch JSON?

  • I confess that I do not know how to solve this.

  • @Diegogo you do not assign value to variable responseText nowhere in your code

  • how so ? I made a console.log(this.responseText) but the return was indefined

Show 4 more comments

1 answer

2

The error refers to the format of your JSON. The function JSON#parse requires the parameter to be a JSON validated. Check the contents of your variable this.responseText and validates whether it is a valid object. A validation tool is JSONLint.

Browser other questions tagged

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