-3

I need to find a way to use a js variable in wordpress query string. I know it involves ajax but i don't know how to go about it. Please help!

 <script>
$(document).ready(function(e) {
var x=$(this).find('.resp-tabs-list li').attr('id');
//alert(x);

});

 $('.resp-tabs-list').on('click',function(e){
        var x   =   $(this).find('.resp-tab-active').attr('id');
        //alert(x);
});

</script>

In the code above, i fetch 'x', which is the category id, based on which i want to fetch posts in a loop.

Fathima
  • 1
  • 1
  • 1
    Possible duplicate of [jQuery Ajax POST example with PHP](http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) – Matheno Feb 12 '16 at 08:12
  • Possible duplicate of [Wordpress - how can I fetch more posts via AJAX?](http://stackoverflow.com/questions/11887760/wordpress-how-can-i-fetch-more-posts-via-ajax) – David Feb 12 '16 at 09:21

1 Answers1

2

You are correct that it does involve ajax. You'll need to do something like the following (I haven't tested it, but it should put you on the right track):

Javascript (assuming you have jQuery loaded, and that you've used PHP to output the admin url as a javascript variable ajaxurl):

$(document).ready(function() {
    bindCategoryFilter();
}

function bindCategoryFilter() {
     $('.resp-tabs-list').on('click',function(e){
        var x   =   $(this).find('.resp-tab-active').attr('id');
        $.ajax({
           type: 'POST',
           url: ajaxurl,
           data: {
              //this is the name of our Wordpress action we'll perform
              'action' : 'get_ajax_posts',

              //this is the important line--send 'x' to the server as category
              'category' : x
           },
           success: function(data) {
            //do whatever with the data you're getting back
            //with the PHP below, it's an array of the post objects
        }
    });
});

This will POST data to our server, with the variable 'category' set to x in the $_POST variable. To access this, in your functions.php you would want to add something like the following:

//add our action hooks--wp_ajax_XXXXX is defined in the ajax query as 'action'
//the second argument is the name of the PHP function we're calling
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
function get_ajax_posts() {
    if(isset($_POST['category'])) {

         //get all the posts in the category, add more arguments as needed
         $posts = get_posts(array('category' => $_POST['category']));

        //data is returned to javascript by echoing it back out

        //for example, to return all of the post objects (which you probably don't wnat to do)
        echo json_encode($posts);

        //we're done
        die();
    }
}

See the wordpress codex for more information about AJAX and Wordpress.

Schiem
  • 589
  • 3
  • 12