AJAX Manufactory

Simplest way to create AJAX application for WordPress

Simplest example

<-- HTML Code (client side) -->
<form class="form form-inline">
  <span class="btn btn-info btn-md clickme-btn">Click Me!</span>
</form>
                
Click Me!

// Javascript (client side)
jQuery(document).ready(function(){
    jQuery('.clickme-btn').on('click', function(){
        jxAction('click_action1');
    });
});
// PHP (server side)
add_action('jx_click_action1', function($jx){
    $jx->alert('Hello, world!');
});

A bit more complex example

<-- HTML Code (client side) -->
<form class="form form-inline tryme-form">
    <input class="form-control tryme-name" placeholder="Enter your name" name="name" value="">
    <span class="btn btn-info btn-md tryme-btn">Try Me!</span>
    <br>
    <span class="tryme-output label label-info"></span>
</form> 

Try Me!

// Javascript (client side)
jQuery(document).ready(function(){
    
    jQuery('.tryme-btn').on('click', function(){
        var data = {
            'name': jQuery('.tryme-name').val()
        };
        jxAction('test_action1', data, function(v){
            if ('backwards' in v) {
                alert("Backwards = " + v.backwards);
            }
        });
    });
    
});
// PHP (server side)
add_action('jx_test_action1', function($jx){
    $name = $jx->data['name'];
    
    if (strlen($name) < 1) {
        $jx->alert('Please enter your name');
    } else {
        $jx->html('.tryme-output', 'Welcome, '.$name.'!');
        $jx->variable('backwards', strrev($name));
    }
});

Some Facts

Whenever you plan to begin developing applications on WordPress using AJAX technology, you have to solve a number of minor issues unrelated to the logic of your application:

  • How to package and transmit data from the browser to the server, so they will not have been distorted?
  • How to transfer data, if they are multi-dimensional array?
  • How to implement a custom processing of AJAX response in case, again, it represents a complex set of data (a typical example - form sending and on-server validation)?
  • How to handle data transition errors?
  • How to debug all this stuff?

Usually these issues generates a lot of spaghetti code, moreover, each new request type requires some customization of code. Managing all of this, you even can forget about the main goal of your code!

We have thought of everything and gathered it in one simple but powerful plugin.

Documentation

Content

  1. Client-side functions
  2. Server-side methods and properties

Client-side functions

There are only two functions which do the thing.

Function Description
jxAction Sends a data using AJAX, receives response and executes sheduled queue from this response. If the callback function specified, jxAction runs it sending "virtual" variables from the server. This function is non-blocking. Returns immediately.jxAction(action, data[, cb])

action is the name of the action, just a string identifier. You will use it at the server side to catch a request.

data is an array or object of data to send. You can push any amount of data here, either one- or multi-level array. However string or null is not allowed.

cb custom callback function which will be called on successful response. Only parameter of this callback is a an array of values sent from server using variable or variables method (please refer "Server-side methods").

Result: always returns null (no return).

jxFormData Returns an object containing key=>value pairs of specified form controls data. Useful to simulate usual form submitting. You can use result as the second parameter for jxAction function.

jxFormData(p)

p is a css selector of node which represents a container form of your inputs. Usually it is a <form> tag, but you can use also <div> as a container.

Result: an object containing key => value pairs of data from specified form.

Server-side methods and properties

You will need to add only one hook action for each "AJAX action".

add_action('jx_<myaction>', function($jx){
   // Your AJAX processing code here
});

This inline function will receive an object $jx of class wpjxmResponse, which is the main processing class. You will need to use its methods and properties to get request data and make a response.

<my_action> is the identifier of the AJAX-action which you set up in the client-side function jxAction.

Properties of object $jx

Property Description
data Returns the data sent from client part with jxAction call.

$jx->data

Example

// Javascript (client side)
jxAction('myaction', {'name': 'John'});
// PHP (server side)
add_action('jx_myaction', function($jx){
    echo $jx->data['name'];  // Outputs "John"
});
has_priv Whether registered user or guest did this jxAction call.

$jx->has_priv

Example

add_action('jx_savedata', function($jx){
    echo $jx->has_priv ? "Registered user" : "Guest";
});

Methods of object $jx

Method Description
alert Shows a standard browser's alert window with a message and [OK] button. It uses an original javascript's alert() method.

alert(string)

Example

add_action('jx_welcome', function($jx){
    $jx->alert('Hello, world!');
});
console Displays an arbitrary data (could be a string or any-dimensional array) in javascript console. Uses console.log() method in javascript. Very useful for debugging.

console(data)

Example

add_action('jx_debug', function($jx){

    global $delay;

    $jx->console(array('time_elapsed' => $delay));
});
html Put any html data inside node(s) with specified css selector. Uses internal jQuery's method jQuery(selector).html(string).html(selector, string)

Example

add_action('jx_button_clicked', function($jx){
    $jx->html('.waiter', '');
});
redirect Make a redirect to specified url. You can also specify a delay (in milliseconds) before redirect actually made. It uses document.location.href = url in javascript.redirect(url[, delay])

Example

add_action('jx_calculate', function($jx){
    $a = $jx->data['a'];
    $b = $jx->data['b'];
    if ($a+$b > 15) {
        $jx->redirect('http://mydomain.com/data_error/');
    }
});
reload Refreshes current page. Nothing special. Uses document.location.reload() in javascript.reload()

Example

add_action('jx_success', function($jx){
    $jx->>reload();
});
script Executes an arbitrary javascript code using eval() method at the client side.

script(code)

Example

add_action('jx_process', function($jx){
    $jx->script('js_function("param");');
});
call Executes a named function at the client side. Parameter is an array of values to be send to specified function.

Example

add_action('jx_custom_call', function($jx){
    $jx->>call('js_function', array('parameter1', 'parameter2'));
});
trigger Triggers an event at the client side. The event will be applied to document object. Parameter is an array of values to be send to specified event.

Example

add_action('jx_trigger_test', function($jx){
    $jx->trigger('jx.custom_event', array('parameter1', 'parameter2'));
});
variable Set up a virtual variable with specified value. Name should be a string, and value can be either boolean, number, string or multidimensional array. At the client side this variable will be passed directly to your callback (in case you are using one in jxAction).

variable(name, value)

Example

// Client side javascript
jxAction('myaction', {'data': 'some string'}, function(v) {
    console.log(v);  // Shows {'var1': 'The value of var1'} in console
});
// Server side PHP
add_action('jx_myaction', function($jx) {
    $jx->variable('var1', 'The value of var1');
});
variables Can be used to set up lots of virtual variables at the same time. The only parameter is an array of variable names (key) and their respective values.

variables(array)

Example

// Client side javascript
jxAction('myaction', {'data': 'some string'}, function(v) {
    console.log(v);  // Shows {'var1': 'The value of var1','abc': 'The value of abc'} in console
});
// Server side PHP
add_action('jx_myaction', function($jx) {
    $jx->variables(array(
           'var1' => 'The value of var1',
           'abc' => 'The value of abc'
     ));
});

Do you have something to say? Any comments, suggestions and criticisms are welcome!

Пожалуйста, укажите Ваше имя
Пожалуйста, введите Ваше сообщение.