Today I wrote my first CakePHP component, well actually I ported it from a PEAR package called Service_JSON. Reason for this was that I needed a way to communicate between PHP and Javascript, I allready used static JSON templates for some basic AJAX action but I wanted a better and easier way to do this and I wanted to be able to decode JSON to PHP.
Read more for the basic documentation how to use the component.
// enable the component in your controller
var $components = array('json');
// convert a complex value to JSON notation, and send it to the view
$value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
$output = $this->json->encode($value);
$this->set('contents', $output);
// prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
// accept incoming POST data, assumed to be in JSON notation
$input = file_get_contents('http://yourjsonfile', 1000000);
$value = $this->json->decode($input);
// It's also possible to do some basic configuration from within the controller
$this->jsonLooseType; // Boolean
// Enables loose typing.
// "{...}" syntax creates associative arrays
// instead of objects in decode().
$this->jsonSuppressErrors; // Boolean
// Suppresses errors.
// Values which can't be encoded (e.g. resources)
// appear as NULL instead of throwing errors.
// By default, a deeply-nested resource will
// bubble up with an error, so all return values
// from encode() should be checked with isError()
The component is licenced under BSD and you can find the source code on CakeForge
Update
James Revillini made a small change in the startup function of the controller as you can see in the comments, thanks for that!. I updated the CakeForge with a new version (0.1.1)
This component did exactly what I was looking for! It’s made it very easy to integrate with the Yahoo UI Datatable component.
I made a few changes to your code in the startup method so that CakePHP would not show undefined variable notices. The new startup method is:
function startup(&$controller) { if(isset($controller->jsonLooseType) && isset($controller->jsonSuppressErrors)) : $this->use = SERVICES_JSON_LOOSE_TYPE | SERVICES_JSON_SUPPRESS_ERRORS; elseif(isset($controller->jsonLooseType)) : $this->use = SERVICES_JSON_LOOSE_TYPE; elseif(isset($controller->jsonSuppressErrors)) : $this->use = SERVICES_JSON_SUPPRESS_ERRORS; else : $this->use = 0; endif; }I tried to enter this as a snippet in Cakeforge, but I couldn’t figure out how to do it without submitting an entirely new snippet. I was trying to make it a version 0.1.1 or something. If you know how to do this, let me know and I’ll post it there.
On behalf of many web developers out there: thanks for your work.
Peace,
James
p.s. the captcha is a bit too difficult to read most of the time.
Two things: First, that last code I posted is junk. Here’s a cleaner version which will actually pay attention to the values of the variables:
function startup(&$controller) {
//initialize variables if they have not been set yet
if (!isset($controller->jsonLooseType)) {
$controller->jsonLooseType = false;
}
if (!isset($controller->jsonSuppressErrors)) {
$controller->jsonSuppressErrors = false;
}
if($controller->jsonLooseType && $controller->jsonSuppressErrors) :
$this->use = SERVICES_JSON_LOOSE_TYPE | SERVICES_JSON_SUPPRESS_ERRORS;
elseif($controller->jsonLooseType) :
$this->use = SERVICES_JSON_LOOSE_TYPE;
elseif($controller->jsonSuppressErrors) :
$this->use = SERVICES_JSON_SUPPRESS_ERRORS;
else :
$this->use = 0;
endif;
}
Second, what is your preferred method of getting data from cake into js variables? I don’t like the way I’m doing it now, which involves putting script tags in my view like this:
//html helper & output data will not be available in external scripts
var author_add_url = ‘url(‘/admin/authors/add’); ?>’;
var data = ;
Thanks,
James
Great to see more people needed this !
I’ll check your changes when i’ve got time and I’ll update it on the CakeForge
My method for getting cake data into JS, isn’t that where json comes in?
Here’s an example using AJAX
The cake view
{
testurl : "/admin/test/blabla"
}
Eval the responsetext
var response = eval(request.responseText);
alert(response.testurl);
Correct my if i’m wrong, it’s just a quick example :D
ps,
the captcha really sucks indeed, I should get another one
Hmm,
What’s the matter with the CakeForge it really works like shit, I’m also trying to add a new codefragment but without any succes.
Awesome component, there’s small bug with the startup part, I changed to :
function startup(&$controller) {
//initialize variables if they have not been set yet
if (!isset($controller->jsonLooseType)) {
$controller->jsonLooseType = false;
}
if (!isset($controller->jsonSuppressErrors)) {
$controller->jsonSuppressErrors = false;
}
if($controller->jsonLooseType && $controller->jsonSuppressErrors) :
$this->use = SERVICES_JSON_LOOSE_TYPE | SERVICES_JSON_SUPPRESS_ERRORS;
elseif($controller->jsonLooseType) :
$this->use = SERVICES_JSON_LOOSE_TYPE;
elseif($controller->jsonSuppressErrors) :
$this->use = SERVICES_JSON_SUPPRESS_ERRORS;
else :
$this->use = 0;
endif;
$this->controller =& $controller;
}
Thx for sharing.
[...] componente muy útil desarrollado Eelco Wiersma en base al paquete de PEAR [...]
[...] an half year ago I created jsonComponent for CakePHP, since then it has been used by quite a few people including [...]
Hi!!
First of all, thanks for the work!
I’m trying to use this component with the Dojo Toolkit but I’m having a problem: the generated json code includes the model level, and I only need the data. I mean, I’m getting this:
{"timestamp":1193692111, "items":[
{"Post":{"id":"1","title":"The title","body":"This is the post body.","created":"2007-11-07 00:44:54"}},
{"Post":{"id":"2","title":"A title once again","body":"And the post body follows.","created":"2007-11-07 00:45:15"}},
{"Post":{"id":"3","title":"Title strikes back","body":"This is really exciting! Not.","created":"2007-11-07 00:45:44"}},
{"Post":{"id":"4","title":"aaaaaa","body":"aaaaaadadasdas","created":"2007-11-12 10:00:45"}}
]}
but I need something like this:
{"timestamp":1193692111, "items":[
{"id":"1","title":"The title","body":"This is ...","created":"2007-11-07 00:44:54"},
{"id":"2","title":"A title once again","body":"And ...","created":"2007-11-07 00:45:15"}
]}
Since I’m a Cake newbe I don’t know if there’s a way to do this or if I have to do it myself. How do you solve this?
Thanks in advance!!
You should manipulate the array CakePHP manually I think. I’m not sure what server side code you’re using so I can’t give you any examples unless you show me some code :)
I created a file a named is jsonsaved it inside the components folder and got this
“Cannot modify header information”
after initializing in app_controller var $components = array(’json’);
whatsthe best solution for this one? thanks
Hi
you did great work. :)
how can i add the following snippet into my cakephp code using your component this is the same code from the jqgrid demo.
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
does the jsonComponent supports the same json output from the original code?
thanks
@peter, are there any spaces or empty lines after ?> on the end of the file ?
@oliver, uhm just use $this->json->encode ?
[...] also had this same problem with the cakephp json component (which I decided to use instead since it would be more portable across php versions than the [...]
[...] JSON Component for CakePHP A nice component click here [...]
[...] Um die Configuraton im marker-file zu verwenden: jsonComponent for CakePHP « Pagebakers. [...]