Wrapper for WordPress' AJAX

1.0.1 2020-02-11 09:58 UTC

This package is auto-updated.

Last update: 2024-04-12 20:07:49 UTC


README

BracketSpace Micropackage Latest Stable Version PHP from Packagist Total Downloads License

Micropackage logo

🧬 About Ajax

This micropackage is a wrapper for WordPress AJAX responses in PHP.

💾 Installation

composer require micropackage/ajax

🕹 Usage

Basic usage

use Micropackage\Ajax\Response;

function ajax_action_handler() {
	$response = new Response();

	// Handle nonce.
	$response->verify_nonce( $action = 'my_action', $query_arg = 'noncefield', $send_if_failed = true );

	// Do some checks and immediately send an error.
	if ( something_is_wrong() ) {
		$response->error( 'Error message' );
	}

	// This is never reached.
	$response->send( 'All good' );

}

Error collecting

You can collect multiple errors in one response.

use Micropackage\Ajax\Response;

function ajax_action_handler() {
	$response = new Response();

	// Do some checks.
	if ( something_is_wrong() ) {
		$response->add_error( 'Error message' );
	}

	// Do some checks.
	if ( something_else_is_wrong() ) {
		$response->add_error( 'Whoah!' );
	}

	// If no error added, the below message will be sent.
	$response->send( 'All good if no errors' );

}

Sending data

use Micropackage\Ajax\Response;

function ajax_action_handler() {
	$response = new Response();
	$response->send( $data_array );
}

📦 About the Micropackage project

Micropackages - as the name suggests - are micro packages with a tiny bit of reusable code, helpful particularly in WordPress development.

The aim is to have multiple packages which can be put together to create something bigger by defining only the structure.

Micropackages are maintained by BracketSpace.

📖 Changelog

See the changelog file.

📃 License

GNU General Public License (GPL) v3.0. See the LICENSE file for more information.