Using Ajax in Blocks of Magento
-
16-10-2019 - |
Question
I am working on list of categories where I need to select one of root categories in the list and after selecting it, it should show the subcategories and so on. SO I am here using ajax calls. As in ajax I am passing variables using get method but how can I a call block.
I have checked in controller for testing and its working fine using this url in ajax as using in controller
xmlhttp.open("GET","http://localhost/magento/weblog/index/fn/?id="+str,true);
then tried to implement on block but i am not able figure out regarding the URL in blocks. How can I use it in Block. and I thik we can not pass the variables from controller to blocks. So finally my question is, How can use Ajax in blocks so that I can use this function in phtml file
Thanks everyone :)
Solution
You need a controller to access the block. In the controller you then call the block with:
$this->loadLayout()
->_addContent($this->getLayout()->createBlock('[module_alias]/[block]'))
->renderLayout();
You can also pass the needed url parameter to you block if you use in the code above:
$this->getLayout()
->createBlock('[module_alias]/[block]')
->setRequestId($this->getRequest()->getParam('id')
The block then processes the request and outputs the data, the output can be formatted as HTML or Json depending on your needs.