Reputation: 2860
I am currently creating a JSON form in a custom Joomla component that makes a call to a function to grab an array of postcodes then returns this to the view. I then want to loop through all the returned postcodes in order to display them. I can't seem to get the jQuery.each loop to loop through the returned values correctly. Here is my code:
view:
jQuery.each(data.postcode, function() {
html += "<span class='btn posctodeInv'>" + v + "</span>";
});
controller:
$club_id = $_POST['club_id'];
$model = $this->getModel('postcodes');
$postcodes = $model->getClubPostcodes($club_id);
header('Content-Type: application/json');
echo json_encode($postcodes);
model:
public function getClubPostcodes($club_id) {
$query = "SELECT postcode FROM #__postcodes_to_club WHERE club_id = '" . (int)$club_id . "'";
$this->_db->setQuery($query);
$result = $this->_db->loadAssocList();
return $result;
}
and the returned json shown in Firebug console:
[{"postcode":"cr4"},{"postcode":"cr5"},{"postcode":"cr6"}]
Can anyone shed any light as to why my loop is throwing up an error? Thanks!
Upvotes: 0
Views: 150
Reputation: 29
var jsonp = '[{"Lang":"jQuery","ID":"1"},{"Lang":"C#","ID":"2"}]';
var obj = $.parseJSON(jsonp);
$.each(obj, function() {
alert( this['Lang']);
});
I think your problem is similar as above. Try above method
Upvotes: 0
Reputation: 1664
Try
jQuery.each(data, function(index, val) {
html += "<span class='btn posctodeInv'>" + val.postcode + "</span>";
});
Upvotes: 2
Reputation: 1344
Try, need index and val parameter to loop in jQuery.each
jQuery.each(data, function(index, val) {
html += "<span class='btn posctodeInv'>" + val.postcode + "</span>";
});
Upvotes: 2