AJAX call to include php file

I have a php file (loopHandle.php) with a wordpress loop inside, which I want to load within a div on my web page.

I make a call using an on click event with a string variable of $date (“2012-6”), this variable is important for my wordpress loop as I will be sorting posts by date.

Read More

I decided to take this step by step, so far I have the AJAX call working and responding with the variable $date to my div.

This is how I see things; on the click event I send the variables I want to use over by using this link:

$link_url = esc_url(wp_nonce_url( admin_url('admin-ajax.php?&action=dynamic_date&my_date='.$date), "dynamic_date_nonce")); ?>

I’m sending the action, nonce and custom variable over to wordpress’ ajax processor (admin-ajax.php) which then triggers a function over in my functions.php. This is where I actually do stuff with the variables I’ve sent.

Now here is the problem I am facing, how do I respond to the ajax call, using the variables I’m sent and reply with my wordpress loop?

Some options I’ve thought about:

$wp_loop = if($loop->have_posts()) { 
while($loop->have_posts()) { 
the_post();
get_template_part( 'content', get_post_format() );
} 
} wp_reset_query();
$response = new WP_Ajax_Response();
$response->add(array(
'what' => 'fulldate',
'data' => $wp_loop)); 
$response->send(); 

That was more of a poke it with a stick and see what happens approach.

Another theory would be to use $date = $_GET['my_date]; in my handleLoop.php, would I be able to retrieve my variable from somewhere that isn’t functions.php? Then could I respond like:

$loopHandle = include(handleLoop.php);
$response->add(array(
'what' => 'fulldate',
'data' => $wp_loop)); 
$response->send(); 

Anyway, I hope I’ve conveyed my problem correctly and of course help is very much appreciated.

Edit: I capture the key-pairs using:

s.data = $.extend(s.data, { action: url.action, _ajax_nonce: url._wpnonce, my_date: url.my_date });

Related posts

Leave a Reply

1 comment

  1. Two questions:

    1) How do you send your data: in the jQuery request, be sure to include your date in the data argument (which you seem to have addressed in your own question by using a GET syntax).

    2) How do you respond? the WP_Ajax_Respond class is for sending XML, possibly a little too heavyweight for you especially since you are most likely returning HTML.

    Instead, try creating a PHP array to store the result of each iteration of your loop, and json_encode your array and return the JSON?

    http://codex.wordpress.org/AJAX_in_Plugins