foreach in javascript for an error json return for a single registry

Asked

Viewed 379 times

0

I’ve got a very boring problem and I don’t know why

Through an ajax request, I get from the server the notifications that the user has not yet viewed (similar to facebook) For this, I use the following code:

$.ajax({
        url: BASE_URL+"ajax/getNotifications",
        type: "POST",
        dataType: "json",
        success: function(response){
            var resultHTML = '';
            response.forEach(function(result)
            {
                resultHTML += '<a href="'+result.href+'" class="no-ajaxy">\n' +
                    '                <div class="user-box">\n' +
                    '                    <div class="user-foto"></div>\n' +
                    '                    <div class="name">'+result.titulo+'</div>\n' +
                    '                    <div class="mail">'+result.mensagem+'</div>\n' +
                    '                </div>\n' +
                    '                </a>';
            });
            $("#justA").hide().html(resultHTML).fadeIn("slow");

        },
        error: function(error) {
            console.log(error + " -  teste");
        }
    }); 

It works correctly when the json result brings back more than ONE notification (which is added dynamically as you can see)

But when it only brings a single notification, I have the following error:

Uncaught Typeerror: Response.foreach is not a Function

I don’t know if javascript is different, but in PHP for example, foreach works if you have one or more elements, but in js it seems to work only when you actually have more than one element What can be done? Thank you


return where the foreach does not work:

{"href":"javascript:void(0)","titulo":"Sem notifica\u00e7\u00f5es!","mensagem":"Atualmente voc\u00ea n\u00e3o possu\u00ed notifica\u00e7\u00f5es"}

Return in which it works:

[{"href":"\/navegar","titulo":"teste horario 04:09","mensagem":"TESTE HORARIO 04:09"},{"href":"pregao\/ativos\/detalhes\/6","titulo":"Preg\u00e3o Finalizado!","mensagem":"Seu preg\u00e3o foi finalizado, confira!"}]
  • Edith the question and put the return, so someone help you.

  • @wmsouza I edited

1 answer

2


The foreach is a function of an element Array. Json can return a array. Ex:

[{"nome": "Valdeir"},{"nome": "Psr"}]`

but can also return a object. Ex:

{"nome": "Valdeir"}`

In your case, he’s returning one element, but as object. In his back-end it is necessary for you to make a check.

Logic:

Se a variável resultado possuir mais de um valor então
    retorna todos como um array
Senão
    cria um array e retorna ele
fim se
  • I ended up noticing that is exactly this, with an element only php is returning an object and not an array, I will check, thank you!

Browser other questions tagged

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