Alright, so I'm trying to learn how to work with AJAX in Wordpress the "right way", via admin-ajax, etc. but I'm kinda going around in circles. I want to load a portfolio item (custom post type) via Ajax - when I do it via jQuery .load() it works fine, but as soon as I try to do it the Wordpress way, it doesn't. Tutorials and StackOverflow questions have only been helpful up to a certain point... I don't know, I just feel kinda dense :-(
This is how far I've gotten, with a little (ahem) tutorial help here and there. Forgive me if there are stupid errors, for I am terrible with this kind of code. It's new to me and all. Also, thanks in advance for any help you can offer :-D
The jQuery:
jQuery(document).ready(function ($) {
$(".getworks").click(function (event) {
event.preventDefault();
if (getpost !== '') {
$.ajax({
type: "POST",
url: MyAjax.ajaxurl,
data: {
'action': MyAjaxRequest,
'getpost': $(this).attr('href'),
},
success: function (data) {
// This outputs the result of the ajax request
$('#portfolio-back').html(data);
console.log(data);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
}
});
});
The PHP:
add_action( 'wp_ajax_MyAjaxRequest', 'MyAjaxFunction' );
add_action( 'wp_ajax_nopriv_MyAjaxRequest', 'MyAjaxFunction' );
function MyAjaxFunction() {
if ( isset($_POST['getpost']) ) {
$getpost = $_POST['getpost'];
if ( $getpost !== '' ) {
echo $getpost;
}
}
die();
}
UPDATE: So I added a preventDefault to the click and I $(this).attr('href') into the ajax call, and now the URL is loaded into the DIV on success, instead of the actual contents.