PHPackages                             ali1/cakephp-json-tools - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. ali1/cakephp-json-tools

ActiveCakephp-plugin[Security](/categories/security)

ali1/cakephp-json-tools
=======================

CakePHP Plugin to help with configuring json responses from the controller, without templates

4.1.0(6y ago)157MITPHPPHP &gt;=7.2

Since May 18Pushed 6y ago1 watchersCompare

[ Source](https://github.com/Ali1/cakephp-json-tools)[ Packagist](https://packagist.org/packages/ali1/cakephp-json-tools)[ Docs](https://github.com/ali1/cakephp-json-tools)[ RSS](/packages/ali1-cakephp-json-tools/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (9)Dependencies (3)Versions (10)Used By (0)

CakePHP Json Tools Plugin
=========================

[](#cakephp-json-tools-plugin)

[![Framework](https://camo.githubusercontent.com/580b6b7df52e2ed143640131d9feacd08c3f33d34c98442752cc5551a47ef2af/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4672616d65776f726b2d43616b65504850253230332e782d6f72616e67652e737667)](http://cakephp.org)[![license](https://camo.githubusercontent.com/e6ab7391dd610f953134256ccfa291d229c06651443bef6784812e980a6fe983/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f616c69312f63616b657068702d6a736f6e2d746f6f6c732e7376673f6d61784167653d32353932303030)](https://github.com/LeWestopher/cakephp-monga/blob/master/LICENSE)[![Github All Releases](https://camo.githubusercontent.com/42cbcc1b21b27e82f1a3975b5ddae4ae4a96e559f1e05220ec2b318219fb0b74/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616c69312f63616b657068702d62727574652d666f7263652d70726f74656374696f6e2e7376673f6d61784167653d32353932303030)](https://packagist.org/packages/ali1/cakephp-brute-force-protection)[![Travis](https://camo.githubusercontent.com/a3d97d8b23579bf5e907675d5e5a4d86a91cc7e46bd32b8c9fd1d8c698c0c042/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f616c69312f63616b657068702d62727574652d666f7263652d70726f74656374696f6e2e7376673f6d61784167653d32353932303030)](https://travis-ci.org/ali1/cakephp-brute-force-protection)[![Coverage Status](https://camo.githubusercontent.com/2d18e1c0cf2da72b400f7f5ebec71aaf8163ead9590fde3a50d861fe307f7ba2/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f616c69312f63616b657068702d62727574652d666f7263652d70726f74656374696f6e2f62616467652e737667)](https://coveralls.io/github/ali1/cakephp-brute-force-protection)

A CakePHP plugin to assist with creating Json responses from controllers.

Json Tools has been created to be used by traditional CakePHP projects which are mostly browser-based, but have a few AJAX or API methods. The Json Tools component makes creating these a breeze.

Features
--------

[](#features)

- A component that quickly lets you set up ajax methods.
- Works with CakePHP's ResponseHandler so you don't have to
- Can be used in methods that sometimes output Html and other times Json depending on request headers, just like normal CakePHP behavior

Requirements
------------

[](#requirements)

- Composer
- CakePHP 4.0+ (see releases for working 3.7+ release)
- PHP 7.2+

Installation
------------

[](#installation)

In your CakePHP root directory: run the following command:

```
composer require ali1/cakephp-json-tools

```

Then in your Application.php in your project root, add the following snippet:

```
// In project_root/Application.php:
        $this->addPlugin('JsonTools');
```

or you can use the following shell command to enable to plugin in your bootstrap.php automatically:

```
bin/cake plugin load JsonTools

```

Now add it to your src/AppController.php or to specific controllers

```
class AppController extends Controller
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('JsonTools.Json');
    }
}

```

Usage (in controller methods that may need to output Json)
----------------------------------------------------------

[](#usage-in-controller-methods-that-may-need-to-output-json)

### Understanding the boiler plate Json output

[](#understanding-the-boiler-plate-json-output)

This component primes ResponseHandler to output something that looks like this:

```
[
    'error' => false,
    'field_errors' => [],
    'message' => '',
    '_redirect' => false,
    'content' => null,
];
```

Which corresponds to a json output of:

```
{"error": false, "field_errors": {}, "message": "OK", "_redirect": false, "content": false }
```

Your controller method can then override these keys or add new ones easily using this component.

### Priming the method with boiler-plate Json output

[](#priming-the-method-with-boiler-plate-json-output)

```
// All Json actions where you want to use this component should have one of the following lines

/**
* The most basic priming. Will set the boiler-plate variables (see below) that can be processed by ResponseHandler
* should there be a json request. If the request is not XHR/JSON, then this method would not have an effect.
*/
$this->Json->prepareVars();

/**
* Will return true if is Json and is POST/PUT, otherwise false
* Can replace something like $this->getRequest()->is(['post', 'put']) that is often used to check if form is submitted.
* You don't need to run prepareVars() if you use this line
*/
if($this->Json->isJsonSubmit()){}

/**
* Will force the output to be Json regardless of HTTP request headers
* You don't need to run prepareVars() if you use this line
*/
$this->Json->forceJson(); // will force the output to be Json regardless of HTTP request headers

/**
* Throw exception if request is not Json or not POST/PUT
* You don't need to run prepareVars() if you use this line
*/
$this->Json->requireJsonSubmit(); // throw exception if request is not Json or not POST/PUT
```

### Setting the JSON output

[](#setting-the-json-output)

Boiler plate output keys (see above) could be overwritten later in your method using one of these methods

```
$this->Json->set('data', $data); // add a new key called data
$this->Json->set('field_errors', $errors); // replace a key
$this->Json->setMessage('Great'); // shortcut to replace message
$this->Json->setError('Bad input'); // sets error to true and message to 'Bad Input' (can be configured to set error to string 'Bad Input' rather than bool true
$this->Json->redirect(['action' => 'index']); // sets _redirect key to a URL (for javascript client to handle the redirect)
$this->Json->entityErrorVars($user); // change the Json output to error: true, and message: a list of validation errors as a string (e.g. Username: Too long, Email: Incorrect email address)
```

Example controller
------------------

[](#example-controller)

```
// UsersController.php
    public function ajaxUpdateUser()
    {
        /*
        Json->requireJsonSubmit() will throw exception if not Json and a Post/Put request and also
        It will also prepare boiler plate variables that can be handled by RequestHandler
                    'error' => false,
                    'field_errors' => [],
                    'message' => '',
                    '_redirect' => false,
                    'content' => null,
        In other words, the action output will be {"error": false, "field_errors": {}, "message": "OK", "_redirect": false, "content": false }
        All of these variables can be overridden in the action if errors do develop or example
        */
        $this->Json->requireJsonSubmit();
        if(!$user = $this->Users->save($this->getRequest()->getData()) {
            // Json->entityErrorVars($entity) will change the Json output to error: true, and message: a list of validation errors as a string (e.g. Username: Too long, Email: Incorrect email address)
            $this->Json->entityErrorVars($user);
        } else {
            // will make the Json output _redirect key into a URL. If you use this, your javascript needs to recognise this (see example javascript)
            $this->Flash->success("Saved");
            $this->Json->redirect(['action' => 'view', $user->id]);
        }
    }

    public ajaxGetUser($user_id) {
        $user = $this->Users->get($user_id);
        $this->Json->forceJson(); // output will be Json. As of this line, the Json output will be the boilerplate output (error: false, message: OK etc.)
        $this->Json->set('data', $user); // the output will now have a data field containing the user object
    }

    public userCard($user_id) {
        $user = $this->Users->get($user_id);
        $this->Json->forceJson(); // output will be Json. As of this line, the Json output will be the boilerplate output (error: false, message: OK etc.)
        $this->set(compact('user')); // for use by the template. don't use $this->Json->set so that the user object does not get send in the output
        $this->Json->sendContent('element/Users/card'); // the Json output will have a 'content' key containing Html generated by the template
    }

    public otherExamples() {
        // Configuration
        $this->Json->setErrorMessageInErrorKey(true); // (default false)
            // true: if $this->Json->setError('error message') is called, the error key and the message key will contain the error message
            // false:  if $this->Json->setError('error message') is called, the error message will be in the message key and the error key will be true and
        $this->Json->setHttpErrorStatusOnError(true); // (default false)
            // by default, the HTTP response is always 200 even in error situations
        $this->Json->setMessage('Great, all saved'); // shortcut to set the message key
        $this->Json->set('count', 5); // set any other json output keys you want to output
    }
```

Example AJAX form
-----------------

[](#example-ajax-form)

This is an example form that corresponds to the ajaxUpdateUser method above.

templates/Users/edit.php

```

```

webroot/ajax\_submit.js

```
/*

Flexible Ajax Form Submission Function
Usage:  or
Will expect json response from server
* If error: true, will alert error message and no further callbacks will occur
* If success (error: false), what happens next depends on the success config
* * (note if server return _redirect key in JSON, then this will take precedence and the page will be redirected)
* * DEFAULT { success: true } By default, the page will just reload on success
* * { success: false } If false is given, do nothing on success
* * { success: function(data, form){} } If a function is given, the data will be passed to that callback function along with the form element. this callback function will be responsible for taking further action
* * { success: $('.results') } If an object(element) is given, then HTML from the JSON content key will be loaded into the given element
* * { success: '/url/to/success' } If a string is given, will redirect to this URL on success

Other config:
blockElement - if element given, only that element is blocked while loading, rather than the whole page

 */

window.ajax_submit = function(form, config){
    config = config || {}; // config is optional
    config.success || (config.success = true);

    let mode;
    if (config.success === true) { // refresh mode
        mode = 'refresh';
    } else if (typeof config.success == 'string') { // redirect mode
        mode = 'redirect';
    } else if (typeof config.success === 'function') { // callback mode
        mode = 'callback';
    } else if (typeof config.success === 'object') { // load HTML mode
        mode = 'html';
    } else { // do nothing mode
        mode = '';
    }
    config.blockElement || (config.blockElement = true); // true = whole page, false = none, element = block only element

    const ajaxOpts = {
        url: $(form).attr('action'),
        data: $(form).serialize(),
        context: form,
        method: 'post',
        headers: {},
        dataType: 'json'
    };

    if($(form).attr('method') && $(form).attr('method') === 'get') {
        ajaxOpts.method = 'get';
    }

    if(typeof $.blockUI !== 'undefined') {
        if(config.blockElement === true){
            $.blockUI({baseZ: 2000}); // modals are 1005
        } else if (config.blockElement) {
            $(config.blockElement).block();
        }
    }

    try{
        $.ajax(ajaxOpts)
            .done(function(data, textStatus, jqXHR){
                if(data.error) {
                    $('.blockUI.blockOverlay').parent().unblock(); // take care of any blocked UI
                    alert(data.message);
                } else {
                    if (data._redirect) {
                        window.location = data._redirect;
                    }
                    else if (mode === 'refresh') {
                        location.reload();
                    } else if (mode === 'redirect') {
                        window.location = config.success;
                    } else if (mode === 'callback') {
                        $('.blockUI.blockOverlay').parent().unblock(); // take care of any blocked UI
                        config.success(data, this); // pass form back
                    } else if (mode === 'html') { // load HTML mode
                        $('.blockUI.blockOverlay').parent().unblock(); // take care of any blocked UI
                        $(config.success).html(data);
                    } else { // do nothing mode
                        $('.blockUI.blockOverlay').parent().unblock(); // take care of any blocked UI
                    }
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                $('.blockUI.blockOverlay').parent().unblock(); // take care of any blocked UI
                console.log(jqXHR);
                if (typeof jqXHR.responseJSON !== 'object' || typeof jqXHR.responseJSON.message !== 'string') {
                    alert(errorThrown);
                } else {
                    alert(errorThrown + ': ' + jqXHR.responseJSON.message);
                }
            }).always(function(data){
            console.log(data);
        });
        return false;
    }catch(err){
        alert('An error occurred');
        console.log(err);
        return false;
    }
};
```

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~34 days

Recently: every ~13 days

Total

9

Last Release

2280d ago

Major Versions

0.4.0 → 4.0.12019-12-23

PHP version history (3 changes)0.1.0PHP &gt;=7.0

0.3.0PHP &gt;=7.1

4.0.4PHP &gt;=7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/637933d952b260bfeeaf8ec8fda92a5acf7eda16df6044fe840f782058a4c7ae?d=identicon)[Ali1](/maintainers/Ali1)

---

Top Contributors

[![Ali1](https://avatars.githubusercontent.com/u/218558?v=4)](https://github.com/Ali1 "Ali1 (20 commits)")

---

Tags

pluginsecuritycakephpajax

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ali1-cakephp-json-tools/health.svg)

```
[![Health](https://phpackages.com/badges/ali1-cakephp-json-tools/health.svg)](https://phpackages.com/packages/ali1-cakephp-json-tools)
```

###  Alternatives

[dereuromark/cakephp-ajax

A CakePHP plugin that makes working with AJAX a piece of cake.

55255.9k1](/packages/dereuromark-cakephp-ajax)[dneustadt/csrf-cookie-bundle

CSRF protection cookie for use with XHR

1379.2k1](/packages/dneustadt-csrf-cookie-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
