Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

The idea is simple. I have a drop-down menu generated with get_categories(). This outputs a list of categories in an unordered list, each in it's own li element.
I'm getting the text values of those li elements when a user clicks them, and based on that i want to create a custom wp_query, that returns posts from that category only. To do this, i`m loading the text value of the list element into a JS variable, send it over to a php file for processing. That php file constructs the string like so:

$ff_query = new WP_Query('posts_per_page=2&category_name='.$_POST['JSvariable']); 

… and ideally should execute it, returning the info from the DB. The error i get is:

"Fatal error: Class 'WP_Query' not found in C:\xampp\htdocs\suply\wp-content\themes\suply\includes\proc_cat.php on line 3"

This is what my 2 files look like:

1) file that sends the ajax request:

<script>
    $(document).ready(function(e) {
        $("#ddmenu li").on('click', function() {
            var cValue = $(this).text();
            $.post("<?php bloginfo('template_url');?>/includes/proc_cat.php", {name: cValue}, function(cat){                
                alert(cat);
                $(".browse-big-slider").append(cat);
            });//end of post
        });//end of click
    });//end of ready
</script>

2) file that should process the

if(isset($_POST)){
        $name = 'posts_per_page=2&category_name='.$_POST['name'];
        $ff_query = new WP_Query('posts_per_page=2&category_name='.$_POST['name']);
      something else, but it won`t reach this part.
}

What can i do to make this work? Or as an alternative, how can i create the type of functionality i want? (basically, a different query, generated dynamically, based on a user selection).

share|improve this question
add comment

1 Answer

That's because when calling a theme template directly you only have what's included/defined in the template file, not the whole WordPress environment.

Some people attempt to fix this by adding an include of wp-header or load etc but this is incredibly damaging

When doing AJAX requests, never call a file in the theme, instead call the WP AJAX APIs.

With the WP AJAX API your file becomes a simple function in functions.php.

I strongly suggest you follow the advice of this article:

http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/#js-global

e.g. PHP:

wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) )
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );

function myajax_submit() {
    // get the submitted parameters
    $postID = $_POST['postID'];

    // generate the response
    $response = json_encode( array( 'success' => true ) );

    // response output
    header( "Content-Type: application/json" );
    echo $response;

    // IMPORTANT: don't forget to "exit"
    exit;
}

JS:

jQuery.post(
    // see tip #1 for how we declare global javascript variables
    MyAjax.ajaxurl,
    {
        // here we declare the parameters to send along with the request
        // this means the following action hooks will be fired:
        // wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
        action : 'myajax-submit',

        // other parameters can be added along with "action"
        postID : MyAjax.postID
    },
    function( response ) {
        alert( response );
    }
);
share|improve this answer
    
Thank you for resonding so quickly :) I stumbled upon that article as well, but didn`t understand much, since i`m very new at both WP and AJAX, but i will give it a go, and hopefully come to a result. Just to be on the safe side though, am i on the right track trying to implement this using WP AJAX APIs (or AJAX for that matter)? –  Radu Andrei Oct 4 '12 at 23:36
    
For listing categories in a dropdown menu? Probably not worth bothering with AJAX, if there's a lot of them then there'll be too many to be navigable, so use autocomplete scripts instead –  Tom J Nowell Oct 5 '12 at 9:01
    
You didn`t understand what i wanted. My needs are: when a user clicks on an element of the drop down, a custom query is created based on his selection. I can`t have a predetermined list of selectable elements, since that list is dynamically generated when the admin creates his categories. –  Radu Andrei Oct 6 '12 at 18:59
    
Then ignore my comment and pay attention to my answer instead for the correct and reliable usage of AJAX in WordPress –  Tom J Nowell Oct 7 '12 at 13:37
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.