If you’re releasing this as a plugin, you absolutely must use the AJAX API. It’s super easy:
/**
* Handle the request and return the result.
*/
function alumni_process_request() {
global $wpdb;
// All your processing code from your original question, except for loading WordPress!
return $data;
}
/**
* AJAX handler for the "alumni" action.
*/
function alumni_ajax_handler() {
global $wpdb;
$data = alumni_process_request();
header( 'Content-Type: application/json; charset=" . get_bloginfo( "charset' ) );
echo json_encode( $data );
exit;
}
add_action( 'wp_ajax_nopriv_alumni', 'alumni_ajax_handler' );
add_action( 'wp_ajax_alumni', 'alumni_ajax_handler' );
That’s the basics. Now we need to make sure we are correctly loading our JavaScript, ensuring we’ll have jQuery loaded, and a global JavaScript variable that will hold the URL for the WordPress AJAX handler:
function alumni_enqueue_script() {
wp_enqueue_script(
'alumni',
plugins_url( 'path/to/script.js', __FILE__ ), // URL path relative to the folder of the PHP script this code is placed in
array( 'jquery' ) // Requires jQuery, make sure it's loaded first
);
wp_localize_script(
'alumni', // Name of script, from above
'alumni', // Name of JavaScript variable
array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action( 'wp_enqueue_scripts', 'alumni_enqueue_script' );
And now for the JavaScript:
!function( $ ) { // Self-executing function closure, will ensure $ is jQuery - might be running in noConflict mode
$( document ).ready(
function() {
$( "#alumni-update" ).submit( // Don't bind to all forms, just ours
function ( event ) {
event.preventDefault();
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
var data = $( this ).serializeArray(); // Will automatically grab all form fields and data
data.push({
name : "create",
value: "1"
});
data.push({
name : "action",
value: "alumni" // This parameter needs to match the wp_ajax_* hook.
});
$.post(
alumni.ajaxUrl, // Use our JavaScript variable "alumni" we defined in wp_localize_script()
data, // POST data
function ( data ) {
// Your form handling
}
);
}
)
}
);
}( jQuery );
The above is assuming a plugin structure like so:
plugin-folder/plugin.php
- PHP code
plugin-folder/path/to/script.js
- JavaScript