json_encode with page_list

Permalink
I have an ajax call that need to receive an array of pages.
What I have until now:
On Submit in PHP
$path = ($_POST['path']);
     $page = Page::getByPath($path);
     $id = $page->getCollectionID();
     Loader::model('page_list');
   $pl = new PageList();
   $pl->filterByParentID($id);
   $results = $pl->getPage();
   echo json_encode($results);


in JS
success : function(data) {
  alert(data.cID);
}


But I receive undefined.

I guess it is because $results it is an object but not an array.
Any suggestions on how to receive pages and get pagename,url.

sergio11ofpp
 
Remo replied on at Permalink Best Answer Reply
Remo
Yes, it's an object, not an array.. You have to loop through all the page objects and create an array.
$pages = $pl->getPage();
$ret = array();
foreach ($pages as $page) {
   $ret[] = array('cID'=>$page->getCollectionID(), 'name'=>$page->getCollectionName());
}

and then return $ret...
sergio11ofpp replied on at Permalink Reply
sergio11ofpp
Thank you for answer My response
[{"cID":"134","name":"About us"},{"cID":"135","name":"Certificates"},{"cID":"136","name":"FAQ"}]


From your code, but still I receive undefined.
Do I need to loop in JS??
Remo replied on at Permalink Reply
Remo
Unless you're happy with just one page you need to loop through the result
JohntheFish replied on at Permalink Reply
JohntheFish
There are existing addons for ajaxed page lists and my own Blocks By Ajax addon can be used with page list templates.