0

I am trying to show subcategories of a category in WordPress using AJAX: when I select a main category, there is a call to WP Ajax and the result is used in showing the subcategories.

So far, I have the client-side code that works when not calling a WP function (this code is in a theme page):

jQuery('#cat-location-main').change(function () {
    var optionSelected = jQuery(this).find('option:selected');
    var valueSelected = optionSelected.val();
    var textSelected = optionSelected.text();
    console.log(valueSelected);
    jQuery.ajax({
      type: 'POST',
      url: ajaxurl,
      data: {
            action: 'myajax-get-subcat',
            category: valueSelected,
            // send the nonce along with the request
            categoryNonce: '<?php echo wp_create_nonce( 'myajax-get-subcat-nonce' );?>'
      },
      success: function(data, textStatus, jjqXHR) {
          console.log(data);
      },
      dataType: 'json'
    });
 });

And I have this in the functions.php:

add_action('wp_ajax_myajax-get-subcat', 'myajax_get_subcat');

function myajax_get_subcat() {
    $nonce = $_POST['categoryNonce'];
    $main_category = $_POST['category'];

    if (!wp_verify_nonce($nonce, 'myajax-get-subcat-nonce'))
        die ( 'Busted!');

    if(function_exists('wp_dropdown_categories')==true) {
        echo 'true';
    } else {
        echo 'false';
    }
    wp_dropdown_categories('taxonomy=category&selected=1&echo=1&orderby=NAME&order=ASC&hide_empty=0&hide_empty=0&hierarchical=1&depth=1&id=cat-location-secondary&child_of='.$main_category);  
    exit;
}

Now I get a "true" on the client side when commenting wp_dropdown_categories line, and I get absolutely nothing when I uncomment that line (PHP crash). Nothing in php error log (WAMP setup).

Also, not working even if I add require_once(__DIR__.'/../../../wp-load.php'); but it works if I use GET in browser (for the functions.php). Any help would be greatly appreciated!

1 Answer 1

1

My problem was because I do not return a json object but an html (actually mixed text and html), and you set jQuery to validate that the response is json, which it isn't.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.