OctoberCMS. Variable Disappears After Ajax Request

- 1 answer

My component template code:


<div id="filter_variations" style="//display: none;">
{{ form_ajax('onAjaxVariations') }}
    <input type="text" id="var_id" name="Filter[id]" value="">
    <input type="submit">
{{ form_close() }}
<div id="partial_service">
    {% partial __SELF__ ~ '::service' %}

in partial i try display "service" variable, and dynamic "variations" variable:

<span>Selected variation: variation[0].name</span>

and it works

Component:enter image description here but if I make a ajax request, variable "service" not display in partial. Why is this happening? And how to avoid this?



Ajax handler is working differently from page life cycle in October.

so when you call page it will initialize page with all the data and all components with its life-cycle methods.

in-short all data is not initialized in ajax request

you want service object inside partial so you are using


but its not been initialized so it will not available in ajax,

to make it available in page code section you need to use onInit method.

function onInit() {
    $this['service'] = // your logic to get service and assign it;

now this service will available inside your ajax handler

public function onAjaxVariations() { // $this->page['service'] will be available and can be passed to view now; }

on normal page refresh it works because all page-cycle function executes, all component life-cycle functions are executed so $this->page['service'] will be available here.

all component life-cycle functions means your onRender function => which calls prepareVars=> which assigns $this->page['service'] (this things are not executed in ajax call)

{ update Preferred solution }

If your code is dependent on page code (page lifeCycle)

in-short code is written inside page markup or in code section and you want to execute it first

inside your ajax handler method you can use this


it will automatically execute all the page code and your all variable will be available now.

public function onAjaxVariations() {
public function onAjaxVariations() {
    // $this->page['service'] will be available