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?
Have you tried setting the
dataTypeproperty of your$.ajaxcall so that your call knows what kind of response to expect? When you set thedataTypeproperty 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
datavariable contains a string, it doesn’t confirm that it’s been parsed into an object with accessible properties.Try this:
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