1

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?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Ben Waine
  • 1,600
  • 3
  • 19
  • 34
  • Just a suggestion: You should really be using `serialize` instead of manually constructing your transport data. http://api.jquery.com/serialize/ – Jamie Wong Aug 15 '10 at 01:11
  • Thanks for the suggestion. I just had a looked at the manual - your right it would be much easier to do this! :) – Ben Waine Aug 15 '10 at 08:35

2 Answers2

3

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>';
Douglas
  • 32,530
  • 8
  • 68
  • 88
  • no offense Douglas but how does this get upvotes, it's not even an answer? – jaywon Aug 15 '10 at 01:31
  • I replied to the "how to correctly access these properties" part of the question. I miss-read his quote from the firebug console, I thought firebug would put quotes around a string, turns out it doesn't. I'll update my answer. – Douglas Aug 15 '10 at 08:33
2

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

Community
  • 1
  • 1
jaywon
  • 7,818
  • 10
  • 36
  • 47
  • Excellent - setting the dataType to JSON did the trick. Thanks for taking the time to answer my question. – Ben Waine Aug 15 '10 at 08:33