I am trying to pass a javascript variable from a range slider into a php query.
So when the user slides range slider to ’44’, the front-page of my wordpress theme shows all posts tagged ’44’.
I want to do this without refresh, so decided to try AJAX, which I’m very new to and struggling to see where I’m going wrong.
So my range slider:
<input id="ex2" type="range" min="0" max="360" step="1" />
In my script.js:
var slider = document.getElementById("ex2");
slider.onchange = function() {
var id = $(this).val();
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/wordpress/wp-admin/admin-ajax.php",
data: {
action:'get_data',
id: id
},
success:function(data) {
alert("result: " + data);
}
});
};
I am then bouncing this value via my functions.php page.. which maybe I can avoid and go straight to my front-page? Code from my functions.php page:
function get_data() {
echo $_POST['id'];
wp_die(); //die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
And then trying to input into my php query on front-page.php:
<?php
$slider = $_POST['id'];
$query = new WP_Query( array( 'tag' => $slider ) );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();?>
<?php the_content();?>
<?php endwhile; endif;?>
I’m very new to PHP and AJAX, not fully understanding the post or echo functions, if someone could help me with my code would be amazing.
Thanks !
2
Answers
It is with the page refresh, but got it working with the POST parameter, don't need any extra code in scripts.js, or functions.php, just on my front-page and for the range slider (in my footer):
My range slider code:
On my front-page:
And is working !
Try Something like this…
test2.php