bodokaiser
bodokaiser

Reputation: 15742

Accessing json does not work

I am using Ajax to receive a JSON update:

    $(document).ready(function(){
    $('form').submit(function(event){
        event.preventDefault();
        var form = JSON.stringify($('form').serializeArray());

        $.ajax ({
            url: '{{ path('PUSChatBundle_add') }}',
            type: 'POST',
            data: form,
            contentType: 'application/json',
            success: function(){
                $.get('{{ path('PUSChatBundle_refresh') }}', function(data){
                    alert(data[1].text);
                });
            }
        });
    });          

});    

Now comes the bad the receiving JSON-Object looks like this:

[{"messageId":43,"text":"ghstgh"}]

and when I now want to access the text with:

alert(data[1].text);

I get undefined....

What am I doing wrong?

Best Regards, Bodo

Upvotes: 0

Views: 832

Answers (3)

Rafay
Rafay

Reputation: 31033

set the dataType to json so that the response is parsed

success: function(){
                $.get('{{ path('PUSChatBundle_refresh') }}', function(data){
                    alert(data[0].text);
                },'json'); //<-- specify the dataType
            }

or manually parse the json

success: function(){
                $.get('{{ path('PUSChatBundle_refresh') }}', function(data){
                    var json = $.parseJSON(data); //<- parse json
                    alert(json[0].text);
                });
            }

example:

var j='[{"messageId":43,"text":"ghstgh"}]';
var json = $.parseJSON(j);
console.log(json[0].text); // or alert(json[0].text);

DEMO

Upvotes: 2

justis
justis

Reputation: 504

Your array only has one element, so you want to use 0 as your index:

alert(data[0].text);

Upvotes: 2

Pointy
Pointy

Reputation: 413682

JavaScript arrays start at 0, not 1.

Upvotes: 2

Related Questions