1

I know this has been asked before, but my case is specific. I am not able to access JSON objects in my code, and I don't know why.

On a website I'm developing, I have an area with user comments. The page loads, and the comment area is populated with a JSON response from the server.

Here's my code:

// Offset = 0
// Limite = 10
// This is a request.
var pedidoComentarios = new PedidoComentarios(0 , 10);

// Get the last comments.
function getUltimosComentarios()
{
    return $.ajax({
        "url": "ultimos-comentarios-ajax",
        "type": "POST",
        "dataType": "json",                                 
        "contentType": "application/json; charset=utf-8",   
        "async" : true,                                     
        "cache" : false,                                       
        "processData" : false,                              

        "data": JSON.stringify(pedidoComentarios),

        "success": function(data)
        {
            alert("Sucesso: " + data);
            alert("Conteúdo: \n\n" + JSON.stringify(data));

            // This will increment the offset.
            pedidoComentarios.offset += pedidoComentarios.limite;

            return data;
        },

        "error": function(xhr , status , error)
        {
            if (xhr.status === 0) 
            {
                alert('Not connect.\n Verify Network.');
            }
            else if (xhr.status == 404) 
            {
                alert('Requested page not found. [404]');
            } 
            else if (xhr.status == 500) 
            {
                alert('Internal Server Error [500].');
            } 
            else if (error === 'parsererror') 
            {
                var tipoResposta = xhr.getResponseHeader("content-type");

                if(tipoResposta.indexOf('html') > -1)
                {
                    window.location.reload();
                }
                else
                {
                    alert('Requested JSON parse failed.');
                }
            } 
            else if (error === 'timeout')
            {
                alert('Time out error.');
            }
            else if (error === 'abort') 
            {
                alert('Ajax request aborted.');
            }
            else
            {
                alert('Uncaught Error.\n' + xhr.responseText);
            }
        }
    });
}

// When the right area is selected, the comments are loaded from the server.
if($('#area-comentarios').length != 0)
{
    alert('Enviando pedido de comentários...');     

    var resposta = getUltimosComentarios();
    var comentarios = resposta.comentarios;

    // This line (447) of code is throwing a error.
    for(var c = 0 ; c < comentarios.length ; c++)
    {
        addComentario(
                $('#area-comentarios #comentarios') , 
                comentarios[c].autor + " - " + comentarios[c].dataHora , 
                comentarios[c].conteudo);
    }
}

Here's the JSON response structure:

{
  "comentarios" : [ {
    "autor" : "Person 001",
    "conteudo" : "Content 001",
    "dataHora" : "10/03/2017 - 15:27:35"
  }, {
    "autor" : "Person 002",
    "conteudo" : "Content 002",
    "dataHora" : "10/03/2017 - 14:28:26"
  }, {
    "autor" : "Person 003",
    "conteudo" : "Content 003",
    "dataHora" : "10/03/2017 - 14:24:23"
  } ]
}

Firefox console is showing me this message:

TypeError: comentarios is undefined[Learn More] codigo.js:447:19

But Firefox seems to have read JSON response:

enter image description here

What am I doing wrong? How can I access a JSON object and it's fields? I already researched the internet how can I do this, but I don't know what I'm doing wrong.

Loa
  • 2,117
  • 3
  • 21
  • 45
  • Not sure why I can't write this as an answer, but the problem is your ajax function returns `data` instead of `JSON.parse(data)`. Your parsing it to print in the console but you need to return that parsed object rather than the string. – user3432422 Mar 14 '17 at 18:48
  • 2
    @user3432422 it doesn't matter what you return, because by the time you do the outer function has long since returned undefined. see dupe. Not to mention, `data` is already an object, not json, so your suggestion would actually throw an error. – Kevin B Mar 14 '17 at 18:51
  • Ah good point, I didn't even notice that. – user3432422 Mar 14 '17 at 18:52
  • @user3432422 Hey. Thanks for your attention. So I did that and Firefox is showing me now one more message: `SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data`. Do you know what this means? – Loa Mar 14 '17 at 18:52
  • @KevinB Hey Kevin, thank you for your time. Seems you marked my question as duplicate. Have you at least read it? It's really **not** a duplicate question from the one you mentioned. Thank you. – Loa Mar 14 '17 at 18:54
  • Yes, i have. Basically, you're trying to return data from an asynchronous callback (the success callback), which is impossible in javascript. You must instead use promises or callbacks, both of which are explained in detail in the dupe. – Kevin B Mar 14 '17 at 18:56
  • @KevinB So, if I do a synchronous callback, will I be able to get the desired data? Oh... I will read the other answer. – Loa Mar 14 '17 at 18:57
  • Yes, but you would still have to change things around quite a bit. You still can't return from the success directly, but you could store that data in a variable and return said variable. Note however that this will result in your page being blocked while the request is being made. On your local machine the block will seem very small, but once this is on a real server with real users, it could block for several seconds or even longer, resulting in a page that feels broken. – Kevin B Mar 14 '17 at 18:58

0 Answers0