Ad

How To Return Ajax Data Request By Id In Octobercms?

- 1 answer

This has to be pretty straight forward by not sure how.

I am building a front end form with categories and subcategories. The code below displays the categories in select box without any issue

Php block

$this['items'] = Cat::where('parent_id',0)->pluck('cat_title', 'id');

Display

<div class="form-group">
  <b><label class="float-left" id="cats" 
for="inputCategory">Category</label></b>
  <select id="category" class="form-control" data-request="onChangeCat" 
 data-request-update="select: '#subcategory'">
    <option selected>Choose...</option>

    {% for key, item in items %}
    <option value={{ key }}> {{ item }}</option>
    {% endfor %}

  </select>
</div>

I have an data-request up there with the following Ajax handler to display subcategories in the next select-box. The partial to be rendered is also in place.

   function onChangeCat()
   {
   $this['subs'] = Cat::where('parent_id', '>',0)->pluck('cat_title', 'id');

    }

The question is how do i write the Ajax handler code to only display subcategories by id of the category. The code above just displays all the subcategories.

Ad

Answer

  1. Give your select a name tag <select name="category">..</select>
  2. Query the subcategories with the posted data accessible via the post() function : e.g Cat::where('parent_id', '=', post('category') )->pluck('cat_title', 'id')
Ad
source: stackoverflow.com
Ad