0

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!

3 Answers 3

2

Try

jQuery.each(data, function(index, val) {
    html += "<span class='btn posctodeInv'>" + val.postcode + "</span>";                       
});
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant this worked. Thanks! Been on holiday for two weeks so don't think my brain is quite working correctly yet!
2

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>";                       
    });

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.