0

I have 2 dropdown lists, when a user select value in the first list, there is an ajax call to a function using WP_query which send results to populate the second dropdown.

My WP_query is not returning any result. I'm new to WP_query so I should have made a mistake somewhere.

The query should return the posts having the meta_key _wpcf_belongs_marque-type_id with the meta_value equal to the parent id sent by ajax. The posts should also have the post_type 'aromes-type'.

Here is the function located in my functions.php:

wp_enqueue_script( 'my-ajax-request', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action( 'wp_ajax_brand_children', 'GetBrandChildren');
add_action( 'wp_ajax_nopriv_brand_children', 'GetBrandChildren');



function GetBrandChildren() {

    $output = '';
    //retrieve POST data sent by AJAX
    $parent_id = $_GET['parent_id'];

    //Define query arguments
    $args = array(
    'post_type'  => 'aromes-type',
    'meta_query' => array(
        'relation' => 'AND',
                array(
                    'key'     => '_wpcf_belongs_marque-type_id',
                    'value'   => $parent_id
                ),
            ),
    'posts_per_page' => -1
    );


    //Create the query
    $the_query = new WP_Query( $args );

    // The Loop
    if ( $the_query->have_posts() ) :
        while ( $the_query->have_posts() ) : $the_query->the_post();
                $output .= '<option>' . get_the_title() . '</option>';
        endwhile;
    else:
            $output = '<option>No flavors found...</option>';
    endif;

    echo $output;

    // Reset Post Data
    wp_reset_postdata();
    wp_die();
}

The JQuery making the call :

//On selected brand, update flavors list
  $(document).on('change', "select[id^='marque']", function() {

        var $brandid =  $(this).val();
        var $brand_dd_id = $(this).attr('id');
        var $flav_dd_id = $brand_dd_id.substr($brand_dd_id.length-1);

        //Make AJAX request, using the selected value as the GET
        $.ajax({
                url: MyAjax.ajaxurl,
                beforeSend: function(){$("#arome"+$flav_dd_id+".ul.select2-results").empty();},
                data: {
                        'parent_id': $brandid,
                        'action': 'brand_children'
                      },
                success: function(output) {
                    console.log(output);
                    $("#arome"+$flav_dd_id+".ul.select2-results").append(output);
                    $("#arome"+$flav_dd_id).trigger("chosen:updated");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status + " "+ thrownError);
        }});

});
  • how is GetBrandChildren gets called? – Reigel Feb 14 '15 at 17:31
  • I updated my post with more information – user3515709 Feb 14 '15 at 18:00
  • Have you checked the network tab(or your console.log()) for what is being returned from the Ajax call? You should be using get_the_title() instead of the_title() by the way. the_title() echoes the title, and this might be breaking your response. – RRikesh Feb 15 '15 at 4:37
  • Also, unrelated to your question, You should hook wp_enqueue_script() and wp_localize_script() as shown in the Codex codex.wordpress.org/Function_Reference/wp_enqueue_script – RRikesh Feb 15 '15 at 4:38
  • Thank you !, I'm getting the good result now,I had serveral problem. First like you said the function the_title() was breaking my HTML, secondly it was not returning results because the content wasn't translated in WPML. For the hook, I had already done that, I was just missing from my post. – user3515709 Feb 15 '15 at 15:45
0

Try using this:

$args = array(
    'post_type' => YOUR_POST_TYPE,
    'meta_query' => array(
        array(
            'key'     => '_wpcf_belongs_marque-type_id',
            'value'   => $parent_id
        )
    )
);

In your loop set an else statement just to sure that you query isn't returning zero results:

if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        $output .= '<li class="active-results">' . the_title() . '</li>';
    endwhile;
else:
    $output = 'No items here :(';
endif;

Hope it helps.

  • Thanks for taking time to answer. The query still return no results. I don't know why because this query in phpmyadmin return rows for my parent_id : select p.id,m.post_id,m.meta_key,m.meta_value from wp_posts p, wp_postmeta m where p.post_type='aromes-type' and p.id=m.post_id and m.meta_key='_wpcf_belongs_marque-type_id' – user3515709 Feb 14 '15 at 18:55
  • I would suggest you to turn on WP_DEBUG_LOG in your wp-config.php, re-test, and see the wp-content/debug.log. This way we can have sure that your code is not breaking when the ajax request occurs. – Bruno Rodrigues Feb 17 '15 at 2:48
  • Thanks bruno, I tried but no log generated. It makes sense because the code is not failing, I'm not just getting the expected result. – user3515709 Feb 17 '15 at 3:22
  • Can you try to echo json_encode($the_query->found_posts); exit; just after the $the_query = new WP_Query( $args );part of your code, and post the result here? Ps. I have the habit to always json_encode my ajax responses, maybe you could try. – Bruno Rodrigues Feb 17 '15 at 3:38
  • 1
    @BrunoRodrigues It could be that it's being set to OR by a filter of some sort. – mor7ifer Feb 18 '15 at 0:06
1

You right Bruno, the AND is optional, I tried without it and it is now working, not sure why, here is the code :

function GetBrandChildren() {

    $output = '';
    //retrieve POST data sent by AJAX
    $parent_id = $_GET['parent_id'];

    //Define query arguments
    $args = array(
    'post_type'  => 'aromes-type',
    'meta_query' => array(
                array(
                    'key'     => '_wpcf_belongs_marque-type_id',
                    'value'   => $parent_id
                ),
            ),
    'posts_per_page' => -1
    );


    //Create the query
    $the_query = new WP_Query( $args );

    // The Loop
    if ( $the_query->have_posts() ) :
        while ( $the_query->have_posts() ) : $the_query->the_post();
                $output .= '<option>' . get_the_title() . '</option>';
        endwhile;
    else:
            $output = '<option>No flavors found...</option>';
    endif;

    echo $output;

    // Reset Post Data
    wp_reset_postdata();
    wp_die();
}
  • Please mark this as answer and not the one that did not work for you. Thank you. – kaiser Feb 18 '15 at 0:35
  • But the answer worked @kaiser, he is using the meta_query as I said. ;) – Bruno Rodrigues Feb 18 '15 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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