My goal here is to load the blogroll into my theme via ajax. But all that I can get as response is 0 (if I omit the die() line, else I get a blank response).
Here is my code:
js ajax:
$.ajax({
url:"http://domain.com/wp-admin/admin-ajax.php",
type:'POST',
data:'action=load_men_blog',
//dataType:'html',
//cache: false,
success: function(html){
$("#b_contentwrapper").empty();
$("#b_contentwrapper").append(html);
}
});
PHP (functions.php) :
function implement_ajax() {
while (have_posts()):
echo "azerty";
endwhile;
die();
}
add_action('wp_ajax_load_men_blog', 'implement_ajax');
add_action('wp_ajax_nopriv_load_men_blog', 'implement_ajax');
Since I have posts in my database, I expect azerty to be returned. But yet I receive a blank response or 0 if I comment the die() line. If I place any echo outside the while loop I get the echo in the expected div, which means that the javascript is working.
Anyone can point me in the right direction?
The issue here is that you haven’t queried any posts. Before
have_posts
try adding something like,query_posts( 'posts_per_page=5' );
Hello and welcome to WPSE. Might I suggest a different approach to implementing AJAX into your theme, it is a bit easier to use as well in my opinion.
Based on this article, the best thing you can do is to use WP’s native
admin-ajax.php
file to run the function. From the code you posted in your question, I came up with this: (I added a nonce and a ‘success’ variable for better control, you can see how it is defined infunctions.php
, also, please do modify to suit your needs, this is an example)some-js-file.js
:functions.php
: