wordpress - get post data using ajax
I'm perusing an attempt to learn ajax and json, and I'm having some
trouble with finding a decent resource. I still have many questions so I'm
mainly looking for a resource.
My aim is to pull content from wordpress posts. I tried looking for
tutorials and discussions but the solutions I found wouldn't work for me
or I didn't like, so I wan't to understand properly what I'm doing wrong.
I have included my efforts so far below, but this is not my primary question.
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' ) ) );
Javscript
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. Not sure how to encode json and return post data
to be used.
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_ajax_request', 'ajax_handle_request');
function ajax_handle_request(){
}
No comments:
Post a Comment