Examples

AJAX Simply

Examples of using the Ajax Simply (ajaxs) plugin. See the documentation at this link.

#1 Return from PHP (echo)

This example shows how in a PHP handler function we can simply output HTML to the screen and JS will receive it as a result...

<!-- HTML -->
<div class="contact"></div>
// JS
ajaxs( 'ajaxs_get_email', { email: '[email protected]' }, function( html ){
	$('.contact').html( html );
} );
<?php
function ajaxs_get_email( $jx ){
	?>
	<p class="myclass"><?php echo esc_html( $jx->email ) ?></p>
	<?php

	// simultaneously output data to the console
	$jx->console( $jx->email );
}

#1.2 Return from PHP (return)

Suppose we need to process the accepted data in PHP and return a data object to JS:

<!-- HTML -->
<div class="my_form">
	<label><input type="checkbox" name="my_check" /> my checkbox </label>
	<select name="my_select">
		<option>Option 1</option>
		<option>Option 2</option>
	</select>
</div>
// JS
ajaxs( 'ajaxs_parse_form', $('.my_form'), function( data ){

	data.done;  //> true
	data.check; //> 'on' if the checkbox is checked
	data.sel;   //> 'Option 1' or 'Option 2'

} );
<?php
function ajaxs_parse_form( $jx ){
	return array(
		'check' => $jx->my_check,
		'sel'   => $jx->my_select,
		'done'  => true,
	);
}

You can return anything: object/array/integer/string/true/false. This example returns an array.

#1.3 Return from PHP ($jx->done|error)

The methods $jx->done(), $jx->error() - send an object and terminate PHP execution. These are analogs of the functions wp_send_json_success() and wp_send_json_error().

<!-- HTML -->
<div class="ajax-respond"></div>
// JS
ajaxs( 'my_function', function( res ){
	var $respond = jQuery('.ajax-respond');

	// success
	if( res.ok ){
		// the $jx->done() method triggered
		$respond.html( 'SUCCESS:' + res.data );
	}

	// error
	if( res.error ) {
		// the $jx->error() method triggered
		$respond.html( 'ERROR:' + res.data );
	}
} );
// PHP
// prefix 'ajaxs_priv_' means the function will run only for WP authenticated users
function ajaxs_priv_my_function( $jx ){
	// some checks
	if( condition is not met ){
		$jx->error( 'error description' );
	}

	if( another condition is not met ){
		$jx->error( 'error description' );
	}

	$jx->done( 'All checks passed!' );

	// this code will not be executed, because $jx->error() or $jx->done() terminate PHP.
	echo 'string that will not be output';
}

#2 PHP handler function (function)

This example shows how to specify which PHP function will handle the request.

// JS
ajaxs( 'my_function' );
// PHP

// variant: prefix 'ajaxs_' - for all users
function ajaxs_my_function( $jx ){
	$jx->log( 'Request triggered with action = my_function' );
}

// variant: prefix 'ajaxs_priv_' - only for authenticated users
function ajaxs_priv_my_function( $jx ){
	$jx->log( 'Request triggered with action = my_function' );
}

#2.2 PHP handler function (static method)

This example shows how to specify a static class method that will handle the request.

// JS
ajaxs( 'MY_Class::my_method' );
// PHP
class MY_Class {

	static function ajaxs_my_method( $jx ){
		$jx->console( 'Triggered method: '. __METHOD__ );
	}

}

Or like this

// PHP
class AJAXS_MY_Class {

	static function my_method( $jx ){
		$jx->console( 'Triggered method: '. __METHOD__ );
	}

}

Note the required prefixes AJAXS_ for the class or ajaxs_ for the method.

These prefixes for clarity can be specified in the called function:

// JS
ajaxs( 'AJAXS_MY_Class::my_method' );

#2.3 PHP handler function (namespace)

This example shows how to specify a static class method located in the namespace myspace.

// JS
ajaxs( '\\myspace\\AJAXS_Class::method' )
// PHP
namespace myspace;

class AJAXS_Class {

	static function method( $jx ){
		$jx->console( 'Triggered method: '. __METHOD__ );
	}

}

#2.4 PHP handler function (hook)

This example shows how to specify a handler using the standard WordPress hook.

// JS
ajaxs( 'my_action_name' );
// PHP
// hook variant - as usual in WordPress
add_action( 'wp_ajax_'.'my_action_name', 'ajax_my_action_name_handler' );
add_action( 'wp_ajax_nopriv_'.'my_action_name', 'ajax_my_action_name_handler' );

function ajax_my_action_name_handler( $jx ){
	$jx->log( 'Request triggered with action = my_function' );
}

Backward compatibility with WordPress hooks allows installing the plugin without rewriting already existing PHP code and while still using the ajaxs() function in JS. The old PHP code will work as before...

#3 AJAX File Upload (single)

<!-- HTML -->
<div class="form">
	<input type="file" name="file_single" />
</div>
// JS
// option: pass the entire form
ajaxs( 'upload_image', jQuery('.form') );

// option: pass the file field
ajaxs( 'upload_image', jQuery('[input name="file_single"]') );

// option: pass the value of the field
var file = jQuery('[input name="file_single"]')[0].files[0];
ajaxs( 'upload_image', { file_single: file } );
// PHP
function ajaxs_upload_image( $jx ){
	$file = $jx->file_single;
	/* $file will contain:
	Array (
		[name]     => Alex-Lynn.jpg
		[type]     => image/jpeg
		[tmp_name] => /home/server/userdata/temp/phpEB56.tmp
		[error]    => 0
		[size]     => 34986
	)
	*/

	// process the received file
}

#3.2 AJAX File Upload (multiple)

You can pass several files in one field file or in several. Let's consider both variants in the example:

<!-- HTML -->
<div class="files-upload-form">
	<p><input type="file" multiple="multiple" name="file_multiple[]" /> - multiple file selection</p>

	<p><input type="file" name="file_split_multiple[]" /> - select one file</p>
	<p><input type="file" name="file_split_multiple[]" /> - select one file</p>
</div>
// JS
ajaxs( 'upload_image', jQuery('.files-upload-form') );
// PHP
function ajaxs_upload_image( $jx ){

	// both variables will contain the same format - standard PHP
	$jx->file_multiple;
	$jx->file_split_multiple;

	/*
	Array (
		[name] => Array (
				[0] => Alex-Lynn.jpg
				[1] => caliyan.jpg
			)

		[type] => Array (
				[0] => image/jpeg
				[1] => image/jpeg
			)

		[tmp_name] => Array (
				[0] => /home/server/userdata/temp/phpBA7C.tmp
				[1] => /home/server/userdata/temp/phpBA8D.tmp
			)

		[error] => Array (
				[0] => 0
				[1] => 0
			)

		[size] => Array (
				[0] => 34986
				[1] => 178154
			)
		[compact] => Array (
				[0] => Array (
					[name]     => Alex-Lynn.jpg
					[type]     => image/jpeg
					[tmp_name] => /home/server/userdata/temp/phpBA7C.tmp
					[error]    => 0
					[size]     => 34986
				)

				[1] => Array (
					[name]     => caliyan.jpg
					[type]     => image/jpeg
					[tmp_name] => /home/server/userdata/temp/phpBA8D.tmp
					[error]    => 0
					[size]     => 178154
				)
			)

	)
	*/

	// process the received files
}

NOTE: Pay attention to the index compact — it is added by the plugin for convenient data processing. Since version 1.1.9.

#3.3 AJAX File Upload (upload progress)

This example shows how to notify the user about file upload progress (how many percent of the file has been uploaded). For this, the uploadProgress parameter is used, into which you need to pass a function that should display the received upload progress somewhere.

For simplicity, the PHP handling of the request is not shown in the example.

<!-- HTML -->
<form id="my_form">
	<input type="file" name="attached_file">

	<button type="submit">Send mail</button>
	<span class="file_upload_progress" ></span>
</form>
// JS
var data = {
	foo : jQuery('#my_form'),
	uploadProgress : function( percentComplete ){
		// display progress in the HTML element .file_upload_progress
		jQuery('.file_upload_progress').text( percentComplete + '%' );
	}
};
ajaxs( 'upload_image', data );

#4 Using $jx->html()

Suppose we have a container where we need to output an authorization form, such a form can be easily obtained with the function wp_login_form().

<!-- HTML -->
<a class="auth_form_btn" href="#">Show login form</a>
<div class="auth_form" style="display:none;"></div>
jQuery(function($){

	$('.auth_form_btn').click(function(ev){
		ev.preventDefault();

		ajaxs( 'show_auth_form' );
	});

});
function ajaxs_show_auth_form( $jx ){

	// add HTML to the block .auth_form
	$jx->html( '.auth_form', wp_login_form([ 'echo'=>false ]) );

	// show the block
	$jx->jseval( "jQuery('.auth_form').show();" );
}

Creating JS code in PHP isn't very proper, but sometimes it is very convenient!

#5 Displaying PHP errors

In WordPress error reporting for AJAX requests is completely disabled and you can see them only through the log file. This is very inconvenient! Anyone who has dealt with it knows what I’m talking about...

AJAX Simply outputs errors of any level to the console, even if it is a fatal error. Error output works only when WP_DEBUG is enabled, so there is no need to worry that normal users might see errors or notices, because on a production project WP_DEBUG is disabled.

For example, imagine that we process an AJAX request and have a fatal error, for instance, misspelled the name of some function.

// JS
ajaxs( 'phpfunction' );
// PHP
function ajaxs_phpfunction( $jx ){
	// a variable that does not exist (notice level error)
	$var['key'];

	// a function that does not exist in PHP (fatal error)
	error_function_name();
}

As a result, the AJAX request will show errors in the browser console, and you won’t have to guess what happened or spend time looking for the cause:

It is important to note that the plugin catches errors from an early stage - from the moment its main file is loaded. For example, if there is an error in the functions.php file it will catch it and output to the console.

Ideally, the plugin should be installed in MU plugins, though there auto-update will not work.

#6 Example of a handler for sending an email with files

<?php

function ajaxs_mailer( $jx ){

	$attached_files = [];

	if( $jx->files ){

		$files = $jx->files[ 'compact' ];

		if( count( $files ) > 5 ){
			$jx->error( [
				'type'    => 'failCount',
				'message' => sprintf(
					__( 'Maximum number of files - 5, you are trying to send %d', 'amcor' ),
					count( $files )
				),
			] );
		}

		foreach( $files as $file ){

			$allowedTypes = [
				'image/jpeg',
				'image/png',
				'application/pdf',
				'application/msword',
				'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
				'application/vnd.ms-excel',
				'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			];

			$maxSize = 10 * 1024 * 1024;

			if( $file[ 'size' ] > $maxSize ){
				$jx->error( [
					'type'    => 'failSize',
					'message' => sprintf(
						__( 'Maximum allowed file size for a single upload - %d MB. File size %s - %d MB', 'amcor' ),
						$maxSize / ( 1024 * 1024 ),
						$file[ 'name' ],
						$file[ 'size' ] / ( 1024 * 1024 )
					),
				] );
			}

			if( ! in_array( $file[ 'type' ], $allowedTypes ) ){
				$jx->error( [
					'type'    => 'failType',
					'message' => sprintf(
						__( 'File upload error %s Only files of formats .jpg, .png, .pdf, .doc, .docx, .xls, .xslx are allowed', 'amcor' ),
						$file[ 'name' ]
					),
				] );
			}

			if( $file && ! $file[ 'error' ] ){
				$attached_file_path = dirname( $file[ 'tmp_name' ] ) . '/' . sanitize_file_name( $file[ 'name' ] );
				@rename( $file[ 'tmp_name' ], $attached_file_path );
				$attached_files[] = $attached_file_path;
			}

		}
	}

	$to      = '[email protected]';
	$subject = 'New application from site';

	$message = "
	<strong>Name:</strong> $jx->name<br>
	<strong>E-mail:</strong> $jx->email<br>
	<strong>Phone:</strong> $jx->phone<br><br>
	";

	$headers = [ 'content-type: text/html' ];

	//$jx->log( $attached_files );

	$sent = wp_mail( $to, $subject, $message, $headers, $attached_files );

	if( $attached_files ){
		foreach( $attached_files as $_file ){
			@unlink( $_file );
		}
	}

	if( $sent )
		$jx->done( __( 'Your request has been sent successfully!', 'amcor' ) );
	else
		$jx->error( __( 'Error sending request.', 'amcor' ) );

}