We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Get the JSON encode result from the Controller to View

I want to put a json encoded result (of ManagementController.php, statisticAction) to the Highchart syntax in view file (stat.phtml) in my Phalcon project. Was originally, in stat.phtml I used:

            ...
            ...
            series: [{
                type: 'pie',
                name: 'Browser share',
                data: []
            }]
        } 
       $.getJSON('data/user_type.php', function(json) {
       options.series[0].data = json;
       chart = new Highcharts.Chart(options);
    });
}); 

with the php data/user_type.php placed in public folder.

user_type.php:

<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
   die('Could not connect: ' . mysql_error());
}
mysql_select_db("mockup_workspace", $con);
$result = mysql_query("SELECT name_type_user, total FROM v_ntype_user where id_admin=1");

$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);

mysql_close($con);
?>

It works when I load, although the data is static. But it still uses native PHP syntax, so I want to use that logic in Managementcontroller. Then I found the issue that $.getJSON that still need URL json file , while I was using ManagementController. Is there a particular js syntax to replace getJSON? What if I want to bring it from the Controller?

ManagementController.php

<?php

 namespace workspace_mockup_2\Controllers;
 use workspace_mockup_2\Models\VnTypeUser as nTypeUser;
 use Phalcon\Mvc\Controller;

 class ManagementController extends Controller {
  ...
  public function statisticAction() {
    $id_admin = $this->session->get('auth');

    // User Type
    $typeUser = nTypeUser::find('id_admin="' . $id_admin . '"');
    $rows = array();
    while($r = mysql_fetch_array($typeUser)) {
       $row[0] = $r[0];
       $row[1] = $r[1];
    array_push($rows,$row);
    } 
    echo json_encode($rows, JSON_NUMERIC_CHECK);
    $this->view->pick("/frontend/user_management_page/stat");
}

I've been looking for a way, such put this in that Controller,

...
$printjson = json_encode($rows, JSON_NUMERIC_CHECK);
$this->view->printjs = $printjson;

and put $printjs variable to replace $.getJSON('data/user_type.php', ... in stat.phtml, but it did not work as well.

Please help :(

Thanks.

I cant see your cited code.

@AlonsoSoto : I've updated it. Please check again, thank's.. :)

ok if I understand well, you have:

a view with javascript code (stat.phtml ) wich makes a json request to get the data (data/user_type.php) , actually you wanna replace this to request by jus one.

Try this:

...
$this->view->setVar('chartData', json_encode($rows, JSON_NUMERIC_CHECK));
...

In your View:


var options = {
    ....
    series: [{
                type: 'pie',
                name: 'Browser share',
                data: {{ chartData }} //Volt!
            }]
};

chart = new Highcharts.Chart(options);
edited Jul '14

@adhe2chazper

You are trying to do the same thing with two different ways and you are mixing implementations. Here is how this works:

You wither use AJAX or you don't. If you don't use AJAX (to get the data) then you need to set a variable in the view layer. If you do, then you need to return the data as an ajax call.

Check these implementations:

SOLUTION 1 - With AJAX:

// Controller
namespace workspace_mockup_2\Controllers;
use workspace_mockup_2\Models\VnTypeUser as nTypeUser;
use Phalcon\Mvc\Controller;

class ManagementController extends Controller {

    ...
    // This action invokes the statistics view
    public function statisticAction() 
    {
        $this->view->pick("/frontend/user_management_page/stat");
    }

    // This function is AJAX and sends the data back
    public function getstatsAction() 
    {
        if ($this->request->isAjax() == true) {

            $id_admin = $this->session->get('auth');

            // User Type
            $typeUser = nTypeUser::find('id_admin="' . $id_admin . '"');
            $rows = array();
            while($r = mysql_fetch_array($typeUser)) {
                $row[0] = $r[0];
                $row[1] = $r[1];
                array_push($rows,$row);
            }

            // A more elaborate response
            $content = json_encode($rows, JSON_NUMERIC_CHECK);

            $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_ACTION_VIEW);

            $response->setStatusCode(200, 'OK');
            $response->setContentType('application/json', 'UTF-8');
            $response->setContent($content);

            $this->view->disable();

            return $response;

        }
    }
}

Now in your view you can have:

            ...
            ...
            series: [{
                type: 'pie',
                name: 'Browser share',
                data: []
            }]
        } 
       $.getJSON('management/getstats', function(json) {
       options.series[0].data = json;
       chart = new Highcharts.Chart(options);
    });
}); 

The above will hit the getstats action (see above) in the Management controller and get the JSON data. The change to your view will be minimal i.e. you will only change the endpoint URL, replacing the data/user_type.php

SOLUTION 2 - No AJAX plain data

// Controller
namespace workspace_mockup_2\Controllers;
use workspace_mockup_2\Models\VnTypeUser as nTypeUser;
use Phalcon\Mvc\Controller;

class ManagementController extends Controller {

    ...
    // This action invokes the statistics view
    public function statisticAction() 
    {
        $id_admin = $this->session->get('auth');

        // User Type
        $typeUser = nTypeUser::find('id_admin="' . $id_admin . '"');
        $rows = array();
        while($r = mysql_fetch_array($typeUser)) {
            $row[0] = $r[0];
            $row[1] = $r[1];
            array_push($rows,$row);
        }

        $content = json_encode($rows, JSON_NUMERIC_CHECK);

        $this->view->setVar('data', $content);

        $this->view->pick("/frontend/user_management_page/stat");
    }
}

Now in your view you can have:

            ...
            ...
            series: [{
                type: 'pie',
                name: 'Browser share',
                data: []
            }]
        } 
        options.series[0].data = {{ data }};
        chart = new Highcharts.Chart(options);
    );
}); 

The above removes the AJAX call and sets the data variable to your options.series[0].data