Registering dependencies
WordPress uses the Dependency API for that. It’s fairly simple: Register & enqueue a script, then pass data that you want to pass from WP/PHP to JS using wp_localize_script()
, which adds a <script>
tag containing an Array to your DOM (exactly before your script gets added to it):
add_action( 'wp_enqueue_scripts', function()
{
$name="handle";
wp_register_script(
$name,
plugins_url( 'assets/ajax.js', __FILE__ ),
[ 'jquery' ],
filemtime( plugins_dir_path( __FILE__ ).'assets/ajax.js' ),
true
);
wp_enqueue_script( $name );
wp_localize_script(
$name,
"{$name}Obj", // This string is what gives you access to below array
[
'ajaxurl' => esc_url( admin_url( 'admin-ajax.php' ) ),
'_ajax_nonce' => wp_create_nonce( "{$name}_action" ),
'action' => "{$name}_action",
'data' => [ /* additional data as array */ ],
]
);
} );
You might notice, that I used wp_create_nonce()
and passed an action attribute to the call for security reasons (verifying the origin of a request in your callback).
How to perform a remote request and fetch XML data
When loading data from a remote request, you should use the WP HTTP API, but with its higher level functions.
Example plugin, that will perform a request and add the result below your footer (both admin and front end):
<?php
/** Plugin Name: (#160775) Fetch XML from TraceNow.net - Part 1 */
add_action( 'shutdown', function()
{
$request = wp_remote_get(
'http://services.tracenow.net/TraceNowAccess.asmx/GetConsignment?'.
join( '&', [
'consignmentNumber' => 'lc0614061377',
'externalAccessGuid' => 'd5dbffb4-0336-44bf-b72c-00fb9aaac759'
],
);
$response = wp_remote_retrieve_body( $request, [
// *additional args
] );
is_wp_error( $response )
AND wp_send_json_error( $response->get_error_code() );
if (
'OK' !== wp_remote_retrieve_response_message( $response )
OR 200 !== wp_remote_retrieve_response_code( $response )
)
wp_send_json_error( $response );
var_dump( wp_send_json_success( $response ) );
} );
This is the easiest way to perform such requests. As you can see, I’m using JSON. XML is gone from WPs HTTP API since some versions as JSON is easier to use.
Hint: wp_remote_*()
takes a second argument, an array of args on which you can read about on Code.
Performing an action
No matter if AJAX-ified (see archive of ajax for more info) or not, you need a form.
<form id="asktracenow">
<input name="consignmentNumber" />
<input name="submit" value="submit" />
</form>
Now that this form submits $_POST
data, you will want to sanitize it, before using it in your URl. You have multiple options depending on how the data is constructed. First we just $cnum = trim( $_POST['consignmentNumber'] )
, then we validate and in case sanitize it.
if ( false !== filter_var( $cnum, FILTER_VALIDATE_INT ) )
{
// do stuff with your absolute, positive integer
// adjust the check to only pass valid data
}
Make sure that you add a lot of weight into this – you never know what you get in return.
AJAXifying things
Simply hook things to the WP action. Summed up this will look close to the following.
// Public or private?
add_action( 'wp_ajax_handle_action', function( $data )
{
check_ajax_referer( $data['action'] );
# @TODO sanitize data here:
// filter_var() filter_var_array() and filter_input()
# @TODO Custom logic here
// Error?
if ( is_wp_error( $thing ) )
wp_send_json_error( $data );
// Success!
wp_send_json_success( $data );
} );
Hint: Put all this in a separate plugin for separation of concerns and portability.
JavaScript AJAX/request handling
To make this answer a bit more complete, here’s a link to another answer by me that explains this in detail and has a huge example Gist attached.