I'm trying to pull content from Wordpress posts AJAX.
I have included my efforts so far below.
Loaded scripts.
wp_enqueue_script( 'my-ajax-request', get_stylesheet_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
JavaScript
jQuery(document).ready(function($) {
$('.ajax a').click(function(event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
type: 'POST',
url: MyAjax.ajaxurl,
data: {'action' : 'ajax_request', 'id': id},
dataType: 'json',
success: function(data) {
console.log(data);
}
});
return false;
});
});
Here I set up my action. How to encode post data as JSON and return?
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');
function ajax_handle_request(){
}
Update:
I'm seeing activity on this post, and it's very old.
Please use the WP REST API instead: https://developer.wordpress.org/rest-api/
I was able to figure this out by setting global $post variable.
Then by encoding the $response.
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');
function ajax_handle_request(){
$postID = $_POST['id'];
if (isset($_POST['id'])){
$post_id = $_POST['id'];
}else{
$post_id = "";
}
global $post;
$post = get_post($postID);
$response = array(
'sucess' => true,
'post' => $post,
'id' => $postID ,
);
// generate the response
print json_encode($response);
// IMPORTANT: don't forget to "exit"
exit;
}
Using jQuery to retrieve the data and output.
jQuery(document).ready(function($) {
$('.ajax a').click(function(event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
type: 'POST',
url: MyAjax.ajaxurl,
data: {'action' : 'ajax_request', 'id': id},
dataType: 'json',
success: function(data) {
console.log(data['post']);
}
});
return false;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With