Skip to content

Instantly share code, notes, and snippets.

@bhubbard
Forked from sfgarza/ajax_class.php
Created September 18, 2021 02:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhubbard/ac1ab9b2514b70097df2fcc44feea88c to your computer and use it in GitHub Desktop.
Save bhubbard/ac1ab9b2514b70097df2fcc44feea88c to your computer and use it in GitHub Desktop.
Boilerplate code for making AJAX calls to wordpress.
<?php
if (!defined('ABSPATH')) {
exit;
}
class ajax_class
{
public function __construct()
{
//Hook = 'wp_ajax_{$action}' where $action must equal the AJAX request's 'action' property.
add_action('wp_ajax_do_something', array($this,'function_do_something'));
//Hook = 'wp_ajax_nopriv_{$action}'. This action is triggered if the client making the request is not logged in to wordpress
add_action('wp_ajax_nopriv_do_something', array($this,'function_must_login'));
}
public function function_do_something() {
// Grab request data
$foo = $_REQUEST["foo"];
//Set results to be sent back to javascript
if(!empty($foo)){
$result['msg'] = $foo;
}
else{
$result['msg'] = 'ERROR';
}
//Send result back to ajax request
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
//if die() function is not called ajax request will hang.
die();
}
public function function_must_login() {
_e( 'You Are Not Logged In', 'textdomain' );
die();
}
}
new ajax_class();
?>
<?php
include_once('ajax_class.php');
// Register style sheet.
add_action( 'admin_enqueue_scripts', 'source_javacript' );
function source_javacript() {
wp_enqueue_script('jquery');
wp_enqueue_script('my_ajax',plugins_url('my_ajax.js', __FILE__), array('jquery'), null, true);
wp_localize_script('my_ajax', 'js_data', array('ajaxurl' => admin_url( 'admin-ajax.php' )) );
}
?>
jQuery(document).ready(function() {
jQuery.ajax({
type : "get",
dataType : "json",
url : js_data.ajaxurl, //URL to your wordpress install's admin-ajax.php file
data : {action: "do_something", foo : "bar" },
success: function(response) {
alert(response.msg);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment