Here's my AJAX request which works fine:
$.ajax
({
url: 'api.php',
type: 'GET',
data: {search_term: data},
dataType: 'JSON',
success: function(data) {
$('#div').html('<p>Constituency: ' + data + '</p>');
},
error: function() {
$('#div').html('<p>Something went wrong. Please try again later.</p>');
}
});
How would I build upon this to allow me to return nested values rather than just data? For example, how would I return constituency_name from this?
{"results": { "constituencies": [{"constituency_name": "Holborn and St Pancras", "member_name": "Frank Dobson", "member_party": "Labour", "member_biography_url": "http://www.parliament.uk/biographies/commons/Frank-Dobson/180", "member_website": "", "uri": "http://findyourmp.parliament.uk/constituencies/holborn-and-st-pancras.json" } ], "members": [] }}
Now what if there are two elements both called constituency_name as here?
{"results": { "constituencies": [{"constituency_name": "Cities of London and Westminster", "member_name": "Mark Field", "member_party": "Conservative", "member_biography_url": "http://www.parliament.uk/biographies/commons/Mark-Field/1405", "member_website": "http://www.markfieldmp.com", "uri": "http://findyourmp.parliament.uk/constituencies/cities-of-london-and-westminster.json" } , {"constituency_name": "Westminster North", "member_name": "Ms Karen Buck", "member_party": "Labour", "member_biography_url": "http://www.parliament.uk/biographies/commons/Ms-Karen-Buck/199", "member_website": "http://www.karenbuck.org.uk/", "uri": "http://findyourmp.parliament.uk/constituencies/westminster-north.json" } ], "members": [] }}
EDIT
Here's my code after trying tymeJV's response:
$.ajax
({
url: 'api.php',
type: 'GET',
data: {search_term: data},
dataType: 'JSON',
success: function(data) {
for (var i = 0; i < data.results.constituencies.length; i++) {
var name = data.results.constituencies[i]["constituency_name"]; //name for this element in the array
$('#div').html('<p>Constituency: ' + name + '</p>');
}
},
error: function() {
$('#div').html('<p>Something went wrong. Please try again later.</p>');
}
});
I get the following error:
Uncaught TypeError: Cannot read property 'constituencies' of undefined