How to use ajax and json encode in Zend Framework 2

I tried a simple ajax aplication using jquery, and the error is every dataobject is a null. Can anyone help me ? Here's mycode :

protected $mysqlAdapter;
protected $studentid;
protected $fullname;
protected $birthdate;
protected $placebirth;
protected $gender;
protected $id_religion;
protected $nm_religion;
protected $stdaddr;
protected $stdphone;
protected $stdcellular;
protected $stdemail;

public function indexAction()
{
    $request = $this->getRequest();
    $response = $this->getResponse();

    $nm_pd = $this->request->getPost('nm_pd');
    $tgl_lahir = $this->request->getPost('tgl_lahir');
    $id_agama = $this->request->getPost('id_agama');
    $nm_agama = $this->request->getPost('nm_agama');

    $dbAdapter = $this->getMysqlAdapter();
    $sql = new Sql($dbAdapter);
    $all = $sql->select();
    $all->from('v_datadetail_feeder');
    $all->where(array('studentid' => 11509002));
    $statement = $sql->prepareStatementForSqlObject($all);
    $result = $statement->execute();

    foreach ($result as $rs) {
        $studentid = $this->$rs['studentid'];
        $fullname = $this->$rs['fullname'];
        $birthdate = $this->$rs['birthdate'];
        $placebirth = $this->$rs['placebirth'];
        $gender = $this->$rs['gender'];
        $id_religion = $id_agama;
        $nm_religion = $nm_agama;
        $stdaddr = $this->$rs['stdaddr'];
        $stdphone = $this->$rs['stdphone'];
        $stdcellular = $this->$rs['stdcellular'];
        $stdemail = $this->$rs['stdemail'];
        $data = array('fullname'=>$fullname,
                      'studentid'=>$studentid,
                      'birthdate'=>$birthdate,
                      'placebirth'=>$placebirth,
                      'gender'=>$gender,
                      'id_agama'=>$id_religion,
                      'nm_agama'=>$nm_religion,
                      'stdaddr'=>$stdaddr,
                      'stdphone'=>$stdphone,
                      'stdcellular'=>$stdcellular,
                      'stdemail'=>$stdemail,
                      );
        $response->setContent(Json::encode($data));         
    }
    return $response;
}

And the result : {"fullname":null,"studentid":null,"birthdate":null,"placebirth":null,"gender":null,"id_agama":null,"nm_agama":null,"stdaddr":null,"stdphone":null,"stdcellular":null,"stdemail":null}

enter image description here

Upvotes: 0

Views: 262

Answers (1)

Vipul
Vipul

Reputation: 655

You have to use ZF2 JsonModel(), enable JsonStrategy inside module.config.php file

'view_manager' => array (
        'strategies' => array (
            'ViewJsonStrategy' 
        ) 
),

and use it like this inside your controller:

$view = new JsonModel($jsonArray);
$view->setTerminal(true); // to disable layout
return $view;

Upvotes: 3

Related Questions