zoinx2012
zoinx2012

Reputation: 175

OctoberCMS. Variable disappears after ajax request

My component template code:

default.htm:

<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>
<div id="partial_service">
    {% partial __SELF__ ~ '::service' %}
</div>

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

<h1>{{service.name}}</h1>
<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?

Upvotes: 0

Views: 817

Answers (1)

Hardik Satasiya
Hardik Satasiya

Reputation: 9693

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

$this->page['service']

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

$this->controller->pageCycle();

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

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

Upvotes: 2

Related Questions