0

I've searched a lot for some direction int his project and even thought I found similar cases, I couldn't find something helpful enough to help me understand this issue. I started working in a custom filter for wp_Query, one for an specific custom field and the other one for category of an specific taxonomy.

In my front end I have a container with two drop downs, kind of like...

<div id="filters">
    <select id="clients">
        <option></option>
        ...
    </select>

    <select id="cats">
        <option></option>
        ...
    </select>
</div>

They are not linked ("cascading"). Both are completely independent, ideally reseting each other to default selection (none) when the other is selected. They just function as a filter for "Clients" and for "Categories of Work". Using jQuery + AJAX, I get the data of the selected item in the drop down and send it to my functions file (using $_REQUEST['clients'] or $_REQUEST['cats']) They go into my function and edit the wp_Query arg. which consequently send the result to a DIV in my page. This is a little snippet (just for the "clients", but is not much different for the other filter):

if( !empty($_REQUEST['client']) && $_REQUEST['index'] != '0' ) {
    $clients = new WP_Query( array(
    'post_type' => 'work',
    'post_status' => 'publish',
    'posts_per_page' => '-1',
    'meta_query' => array(
        array(
            'key' => 'client_name',
            'value' => $_REQUEST['client'],
            ),
        ),
    ));
    callD( $clients );
}

And here is my ajax.js file, which deals with the listening/processing of the events in the dropdown (in the two dropdown):

//select the container with the two dropdowns
jQuery('#client-select').bind('change', function(event) {
    $.ajax({
        type: "POST",
        url: '/wp-admin/admin-ajax.php',
        data: {
            'action': 'example_ajax_request',
            'client': $('option:selected', this).attr('value'),
            'index': $('option:selected', this).index(),
        },
        success: function(__data) {
            if (__data === '') return; // or leave default empty message
            $('#all-work-thumbs-container').html(__data).fadeIn('slow');
        },
        error: function(errorThrown) {
            console.log(errorThrown);
        },
    });
});
jQuery('#cat-select').bind('change', function(event) {
    //AJAX request
    $.ajax({
        type: "POST",
        url: '/wp-admin/admin-ajax.php',
        data: {
            'action': 'example_ajax_request',
            'index': $('option:selected', this).index(),
            'cat': $('option:selected', this).attr('value'),
        },
        success: function(__data) {
            if (__data === '') return; // or leave default empty message
            console.log($('option:selected', this).attr(
                'value'));
            $('#all-work-thumbs-container').html(__data).fadeIn('slow');
        },
        error: function(errorThrown) {
            console.log(errorThrown);
        },
    });
});

I'm very new to this, but I was wondering the best approach to simplify my ajax.js file, which right now it contains two jQuery functions. How can I make it maybe condensed into just one ajax request? How can I approach the logic of reseting one of the dropdown when the other is selected?

I apologize if this question is too simple, maybe I'm just not completely understanding how to approach it in this context.

Thank you!

mmarquez
  • 147
  • 3
  • 11

1 Answers1

0

If you really want to use one AJAX function, you can simplify things by placing the AJAX call in its own function and calling it within the on change events, passing any required args.

var sendRequest = function( data, callback ) {
    jQuery.ajax({
        url: '<?php echo admin_url("admin-ajax.php"); ?>',
        type: 'POST',
        data: data,
        success: function( response ) {

            if( callback != undefined )
                callback( response );   //pass the response to your callback function

        }
    });
}

jQuery('select').bind('change', function(evt) {

    //build data
    var data = {};

    //send the request
    sendRequest( data, function( response ) {
        //do something with the response, like reset the select boxes

    } );

});

In terms of resetting the select boxes, you could move this to a function as well

var resetSelect = function( select ) {

    jQuery(select).find('option:first').attr('selected', true)

}

You would need to pass the correct select element to the function. Some other recommendations:

  1. Use either $_GET or $_POST. $_REQUEST is making it that much easier for the bad guys.
  2. Check out admin_url('admin_ajax.php') for Wordpress. I utilized it in my code here. Also, Wordpress AJAX.
  3. Most importantly, sanitize and validate your data.

Still some pieces for you to figure out, but hope that helps.

Chris
  • 4,762
  • 3
  • 44
  • 79
  • Chris -- your response is **excellent**, I can already make sense of how to put the AJAX in a single function. (Is this better? Or having two functions is acceptable?) -thanks for the recommendations!!! – mmarquez Oct 22 '15 at 02:00
  • I don't think this is really a question of better, but many would argue yes (http://stackoverflow.com/questions/6453235/what-does-damp-not-dry-mean-when-talking-about-unit-tests) – Chris Oct 22 '15 at 02:01