Ajax error - unexpected end of data

Asked

Viewed 126 times

1

I’m trying to figure out what’s going on with the ajax code below. If the string comes with data, it works correctly, but if it comes empty, error occurs:

JSON.parse: Unexpected end of data at line 2 column 1 of the JSON data

If I give an Alert on var dados = JSON.parse(xmlreq.responseText); which is where the error occurs, it is empty, but does not enter the exception I made: if (xmlreq.responseText == "") {

Any idea where I might be going wrong?

UPDATE

Complete ajax:

/**
  * Função para criar um objeto XMLHTTPRequest
  */
 function CriaRequest() {
     try{
         request = new XMLHttpRequest();
     }catch (IEAtual){

         try{
             request = new ActiveXObject("Msxml2.XMLHTTP");
         }catch(IEAntigo){

             try{
                 request = new ActiveXObject("Microsoft.XMLHTTP");
             }catch(falha){
                 request = false;
             }
         }
     }

     if (!request)
         alert("Seu Navegador não suporta Ajax!");
     else
         return request;
}

//Não executa nada até a execução terminar
var requestActive = false;

function getDados() {
    if (requestActive) return;
    requestActive = true;
    // Declaração de Variáveis
    /* Caso for necessário passar mais parametros além do nome
     * basta adicionar uma variável aqui e editar no GET
     */
    var ids = ["usuario", "senha", "email", "admin", "cod_setor", "nome_completo", "ativo", "habilitacao", "categoria"];
    var cracha = document.getElementById("cracha").value; //CAMPO QUE VEM DO INDEX.PHP
    var result = document.getElementById("content"); //DIV DE RETORNO DOS DADOS
    var xmlreq = CriaRequest();

    // Exibe a mensagem de progresso
    //result.innerHTML = '<img src="images/Progresso.gif"/>';
    ids.forEach(function (id) {
        document.getElementById(id).value = 'Aguarde...';
    });

    // Iniciar uma requisição
    // Se for colocar mais variáveis, é aqui. Exemplo: processa.php?txtnome=" + nome + '&admissao=' + admissao
    xmlreq.open("GET", "processaMotorista.php?cracha=" + cracha, true);

    // Atribui uma função para ser executada sempre que houver uma mudança de estado
    xmlreq.onreadystatechange = function () {
        // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4)
        if (xmlreq.readyState == 4) {
            // Verifica se o arquivo foi encontrado com sucesso
            if (xmlreq.status == 200) {
                //Se o retorno foi vazio do Oracle
                if (xmlreq.responseText == "") {
                    document.getElementById("nome_completo").focus();
                    ids.forEach(function (id) {
                        document.getElementById(id).value = '';
                    });
                //Se encontrou dados
                } else {
                    //Aqui recebe os dados do processa.php, abre e aplica nos campos desejados
                    var dados = JSON.parse(xmlreq.responseText);
                    // função para preencher os campos com os dados
                    ids.forEach(function (id) {
                        document.getElementById(id).value = dados[id];
                    });
                }
            } else {
                result.innerHTML = "Erro: " + xmlreq.statusText;
            }
        }
        requestActive = false;
    };
    xmlreq.send(null);
}

  • You are saying that the end of the data is on line 2, so the answer is not empty. Try using a debugger to see what is happening.

  • No firebug appears nothing. Error appears, but no data.

  • Try to add console.log(xmlreq.responseText); and then check the console.

  • Or Put a breakpoint on that line and parse the value of the variable before letting it run.

  • I did this, the variable comes null, but goes straight through if, as if there was something in it. I put the console.log(xmlreq.responseText); but nothing has changed

  • @Diego if it comes null(NULL), you should do this second check tbm. NULL is different from Void. Change your if to check if it is coming Empty, null or blank("",null, " ")

  • I did the 3 tests and returned the same error. I have no idea what happened, but other 3 ajax that use basically the same syntax also stopped.

  • @Diego Use a debugger to stop execution before entering IF and look at the value exact from the inspector. Console.log can be misleading because several things have a representation that seems empty.

  • Which debugger could use @Pablo?

  • 1

    The debugger of your favorite browser. In Firefox, press F12, go to the Debug tab and click the left side of the IF line to place a stop point there. When your code runs, when it reaches that line, the execution to.

  • Diego, the problem has been solved?

  • Yes, I found that I had an extra space where I mounted the string. I removed it and started working again.

Show 7 more comments
No answers

Browser other questions tagged

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