user3544190
user3544190

Reputation: 39

Zend 2 Ajax JSON multiple data

I am trying to figure out how to display a few elements by Ajax using JSON. I followed this Using ajax in zend framework 2 and everting is working fine, but now want to pass for example 10 object by JSON

public function indexAction()
{   
    $result = new JsonModel (array(
        'fototable' => $this->FotoTable->getFotos()
        )
    );
    return $result;
}

and then loop in js and display the data. The problem is if I do above code. I do not get any Json output. I tried to serialize the data but i get the error that PDO statment can not be serialized.

Here is my Fototable class:

<?php

namespace Media\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;
use Zend\Db\Adapter\Adapter;

class FotoTable extends TableGateway{

    public static $tableName = 'media';

    public function addFoto(array $data)
    {
        return $this->insert($data);
    }

    public function updateFoto(array $insertData, $id)
    {
        return $this->update($insertData, array('id' => $id));
    }

    public function getFotos()
    {
        $select = new Select();
        $select->from(self::$tableName);
        $resultSet = $this->selectWith($select);
        $resultSet->buffer();

        return $resultSet;      
    }

    public function getFotoById($id)
    {
        $select = new Select();
        $select->from(self::$tableName);
        $select->where(array('id' => $id));
        return $this->selectWith($select)->current();
    }

    public function getFotosByObject($project)
    {
        $select = new Select();
        $select->from(self::$tableName);
        $select->where(array('object_id' => $project));

        return $this->selectWith($select);
    }
}

Upvotes: 1

Views: 475

Answers (1)

Otto Sandstr&#246;m
Otto Sandstr&#246;m

Reputation: 745

in

public function getFotos()
{
    $select = new Select();
    $select->from(self::$tableName);
    $resultSet = $this->selectWith($select);
    $resultSet->buffer();

    return $resultSet;      
}

You return the Resultset which is not an array. You can either do

return $resultSet->toArray();

sometimes to array is not available so you can iterate over the resultSet to an array

$array = array();
foreach ($resultSet as $row) {
    $array[] = $row
}
return $array;

Upvotes: 3

Related Questions