AJAX in WordPress (the usual nightmare)

Add this to your ‘functions.php’ file:

wp_localize_script( 'portfolio-application', 'my_ajax_object', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url( 'admin-ajax.php' ),

// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
// 'security' => wp_create_nonce( 'my-special-string' )
));

function get_data() {
$the_posttype = $_GET['posttype'];

$args = array(
'numberposts' => -1, // -1 is for all
'post_type' => $the_posttype, // or 'post', 'page'
'orderby' => 'title', // or 'date', 'rand'
'order' => 'ASC', // or 'DESC'
//'category' => $category_id,
//'exclude' => get_the_ID()
// ...
// http://codex.wordpress.org/Template_Tags/get_posts#Usage
);

$cases = get_posts( $args );

header('Content-Type: application/json');

echo json_encode( $cases );
wp_die();
}

add_action('wp_ajax_get_cases', 'get_cases');
add_action('wp_ajax_nopriv_get_cases', 'get_cases');

Where ‘the-application’ is the enqueued script from where you make the $.ajax … or whatever call.

Add this to your javascript application (whatever file it may be ‘build’ into using a build process like gulp or what ever):

let config = {
action : 'get_data', // The metod in the function.php file to call
posttype : 'case' // Arbitrary data to pass to the call
};

$.ajax({
url : my_ajax_object.ajaxurl,
type: 'GET',
data : {
'action' : config.action,
'posttype' : config.posttype
}
}).done(function ( response ) {
// Handle response
}).fail(function ( err ) {
// Handle error
});