Ben Waine
Ben Waine

Reputation: 1648

Unable to access the properties of an object returned from an ajax call

I'm quite new to JS and jQuery.

I have a problem accessing the properties of an object returned from the jQuery ajax method.

As you can see in the code below I'm trying to use the properties of the object 'data' in the success call back function to create a table row, which I then try and add to a table.

$('#add_comp').submit(function(){
        
        var startDate = $('#form_startDate').val();
        var initPrize = $('#form_init_prize').val();
        var active    = $('#form_active').val();

        var dataString = 'startDate=' + startDate + '&startPrize=' + initPrize + '&active=' + active;

        $.ajax({
            type: 'POST',
            url: "/admin/competition/add-competition",
            data: dataString,
            success: function(data, textStatus, xhr){
                console.log(data);
                console.log(data.startDate);
                console.log(data[startDate]);
                console.log(data['startDate']);
                
                var tr = '\n\
                          '+ data["startDate"] +'\n\
                          '+ data.active +'\n\
                          '+ data.currentPrize +'\n\
                          ';
                $('#competition_table').find('tr:last').after(tr);

            },
            error: function(){
                alert('There has been an error, please consult the application developer.');
            }

        });

The success function is a bit of a mess as I'm trying a number of different ways of accessing the properties of the data object.

The first console.log(data) line returns the following in Firebugs console:

{"competitionId":null,"startDate":"08\/02\/2010","endDate":null,"winner":null,"participantPool":"4c6729aa8c8fb","active":1,"startPrize":"350","currentPrize":"350"}

This confirms the data object is there and it has the correct properties.

I assume I should be able to access the individual properties using 'data.propertyName' however all subsequent console.log() calls return 'undefined'.

How to correctly access these properties and use them to build the table row?

Upvotes: 1

Views: 3321

Answers (2)

Douglas
Douglas

Reputation: 37781

To read properties on the data object, data.startDate and data["startDate"] should both work.

As pointed out by jaywon, the problem is that your data object is a string, not an object. You can confirm this by adding another console.log line, like this:

console.log(typeof data);

That will print out "string" instead of "object". You can print out properties of the string object in the normal way, for example the number of characters is:

console.log(data.length);

To get jQuery to parse the JSON for you, you need to either set the dataType property as described by jaywon, or include this content-type header when you serve up your json:

Content-Type:text/json

If you include this header from the server, then you're example code will print the correct properties to the console.

Finally, to add a row to your table, you need to append a table row instead of a plain text string, so you should change your var tr = ... line to this:

var tr = '<tr>' +
             '<td>' + data.startDate    +'</td>' +
             '<td>' + data.active       +'</td>' + 
             '<td>' + data.currentPrize +'</td>' +
         '</tr>';

Upvotes: 3

jaywon
jaywon

Reputation: 8234

Have you tried setting the dataType property of your $.ajax call so that your call knows what kind of response to expect? When you set the dataType property to json jQuery knows to parse the JSON response into an object, otherwise it doesn't know if you're receiving back a text string, HTML, or JSON, etc... from the server.

This confirms the data object is there and it has the correct properties. Actually, that only confirms that your data variable contains a string, it doesn't confirm that it's been parsed into an object with accessible properties.

Try this:

$.ajax({
            type: 'POST',
            url: "/admin/competition/add-competition",
            data: dataString,
            dataType: "json" //add this line
            success: function(data){ //only the data object passed to success handler with JSON dataType
                console.log(data);
                console.log(data.startDate);
                console.log(data[startDate]);
                console.log(data['startDate']);

                var tr = '\n\
                          '+ data["startDate"] +'\n\
                          '+ data.active +'\n\
                          '+ data.currentPrize +'\n\
                          ';
                $('#competition_table').find('tr:last').after(tr);

            },
            error: function(){
                alert('There has been an error, please consult the application developer.');
            }


        });

Alternatively, you can parse the JSON response yourself with an external script like JSON2.

Here is a good thread also with examples of further problems you may encounter with the server possibly not sending back the correct response header. jQuery won’t parse my JSON from AJAX query

Upvotes: 2

Related Questions