I found it
First, I want to note that the approach I mentionned in my question is bad according to almost tutorials talking about AJAX in wordpress. So I decided to change the approach and use the built-in AJAX of WordPress.
In other words, the best way for my situation is to use the wp-admin/admin-ajax.php. AJAX requests should be directed to this file. I know the “admin” part of the file name is a bit misleading. but all requests in the front-end (the viewing side) as well as the admin panel can be processed in admin-ajax.php, with a lot of benefits, especially for security.
The steps are:
1.The JavaScript code that submits the AJAX request should look something like this:
$(document).ready(function() {
$('.select2').change(function(e) {
e.preventDefault();
var v = $('.select2 option:selected').val();
$.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php", // check the exact URL for your situation
dataType: 'html',
data: ({ action: 'nextPrevious', id: v}),
success: function(data){
$('#nav-above').html(data);
},
error: function(data)
{
alert("Your browser broke!");
return false;
}
});
});
});
Note that you should respect the requeriements of WordPress in putting the JS script (generally in footer.php
before wp-footer()
)
2- Handling the action:
in functions.php
of your theme (or directly in your plugin file), add:
add_action('wp_ajax_nextPrevious', 'nextPrevious');
add_action('wp_ajax_nopriv_nextPrevious', 'nextPrevious');
and define in the same file nextPrevious
callback function like this:
function nextPrevious() {
$p= $_GET['id'];
$my_query = new WP_Query();
$my_query->query(array( 'post__in' => array($p)));
if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="nav-previous"><?php previous_post_link( '%link', '<img height="34" src="' . get_bloginfo("template_directory") . '/images/previous.png" />' ); ?></div>
<div class="nav-next"><?php next_post_link( '%link', '<img height="34" src="' . get_bloginfo("template_directory") . '/images/next.png" />' ); ?></div>
<?php endwhile;
endif;
wp_reset_query();
die();
}
Do not forget the die function, it is mandatory (thank you Bainternet
).
For more details about AJAX in WordPress, Google first page tutorials are good.