WordPress AJAX

Asynchronous JavaScript and XML, commonly known as AJAX plays an important role in designing functional WordPress plugins. It allows WordPress plugins to download data without refreshing the page each time for fetching data from the server. It does this by transferring data in the backend.

References

Example

In this example plugin, consider how wp_ajax has been used to mix PHP and JavaScript, then provide functionality similar to the Heartbeat API to update with a random color and random words from a proxied remote HTTP API every 3 seconds.

Note in the example use of apply_filters() to unify data sent to wp_localize_script() (initialData) and $.getJSON() (newData).

In contrast, notice the difference in this version of the plugin, where the REST API is used instead of wp_ajax for newData. Notice especially line 71, where wp_json_encode() is no longer called for data output by the REST API — JSON encoding is handled automatically. Also notice use of get_rest_url() on line 16 — this resolves the path to /wp-json/ even if the JSON endpoint has been modified with the rest_url_prefix filter.