Wordpress ajax returning html

I am using WordPress ajax to load subcategories dynamically.

Here's my code

Php Code

  function techento_getsubcat() {
  $category_name = $_POST['catname'];
  $cat_id = $_POST['catid'];
  return wp_dropdown_categories( 'show_option_none=Choose a Sub              Category&tab_index=10&taxonomy=category&hide_empty=0&child_of=' . $cat_id . '' );

  }
  add_action('wp_ajax_techento_getsubcat', 'techento_getsubcat');
  add_action('wp_ajax_nopriv_techento_getsubcat', 'techento_getsubcat');

      

Jquery

        jQuery(document).ready(function(){
   $('#cat').change(function(e){
   alert("changed");

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: pcAjax.ajaxurl ,
        data: { 
            'action': 'techento_getsubcat', //calls wp_ajax_nopriv_ajaxlogin
          'catname':    $('#cat option:selected').text(), 
            'catid':    $('#cat option:selected').val() },
        success : function(response){
                 alert(response);
             console.log(response);

           $("#subcats").html(response);

        }
    });
    e.preventDefault();

      });
  });

      

The problem with the above code is php is returning raw html no matter what it wants to return

even if you set it to

    return true;

      

it returns the original html of the generated subcategories plus '0'

+3


source to share


1 answer


You are missing shortcode in $

jQuery(document).ready(function($){

      

The Ajax callback is better handled wp_send_json_success()

so we don't have to worry about return

either echo

, exit

or die

. To do this, set echo

to false in the dropdown arguments :



function techento_getsubcat() {
    $cat_id = intval( $_POST['catid'] );
    $args = array(
        'hide_empty'         => 0, 
        'echo'               => 0,
        'child_of'           => $cat_id,
        'taxonomy'           => 'category'
    );
    $data = wp_dropdown_categories( $args );
    wp_send_json_success( $data );
}

      

If Ajax succeeds, use response.data

:

success : function(response){
    console.log(response.data);
}

      

+4


source







All Articles