How to use `foreach()` in ajax call

Question

I have written a code for retrieving data from the database using the ajax for WordPress. The following code is the one written in the functions.php. The code is for getting the id and names of subcategories under a category id which is defined as $cat . The result, i need to display as a drop down list

function fetchData(){
  global $wpdb;
    $catId = $_POST['key']; // value from the ajax

        // Now we want to JSON encode these values to send them to $.ajax success.
      if($catId){
         $result_fromDB = $wpdb->get_results("SELECT * FROM  sub_category where categor_id = '".$catId."'");
          echo "<option value='".$catId."' >".$catId."</option>"; //This line is returned in ajax. this is a test code
         foreach ($result_fromDB as $subcat) {
                           echo "<option value='".$subcat->id."' >".$subcat->sub_category_name."</option>"; // This line doesnt returned, getting only **<option></option>** in console
          }
      }

        die();
    }

The code corresponding to the ajax is,

jQuery.ajax({
    type: 'POST',
    url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
    data: {
         'key' : catId,
        'action': "fetch_data" // very important
    },
    success : function (data) {
             console.log(data);
             jQuery('#sub_cat').html(data);
            }
  });

Can anyone give the reason and answer for not getting the data in the foreach()/loop

0
, , , avs 3 years 2020-06-05T19:10:34-05:00 0 Answers 102 views 0

Leave an answer

Browse
Browse