JSON RPC Call With Odoo Web Controller
May 27, 2017
Web Controller provides facility to integrate Odoo Front-end like websites and related Modules with Odoo Backend (Sales, Purchase, CRM, HR etc).
Web controller contains two types of requests as parameter :
HTTP
JSON
We can create Web Controller using any of the above request types. To know more about HTTP Web Controller in detail please visit : http://www.surekhatech.com/blog/web-controller-in-odoo-v9
Here I am going to explain how to create a JSON controller in Odoo 9. JSON controller basically uses JSON format data which is passed/retrieved with the server. We can also restructure this data in our desired format before passing to the webpage. Here are the complete steps to implement a JSON controller with Odoo.
Step 1: Add script.js file as per below module structure. We will be writing front end code for JSON Web Controller in this file.
|?? Module
| |? controller
| | |? __init__.py
| | |?main.py
| |? static
| | |? src
| | | |? js
| | | | |? script.js
| |? view
| | |?template.xml
| |? data
| | |?data.xml
| |? __openerp__.py
| |? __init__.py
Step 2: Add below content in script.js file which would send JSON data to the python code :
# Define Ajax variable var ajax = require('web.ajax'); # Json rpc call ajax.jsonRpc("/some_url", 'call', { 'input_data' : $('#input).val(), }) # if data is received from python(odoo backend) [optional] .then(function (data) { var output_data = data[‘output_data’] #Output from controller in form of data dictionary $("#output").html(output_data); }); |
Step 3: Add one method in the controller (main.py) which could handle the Ajax request from Web Controller. This method would also return the output data in JSON format.
#---------Data processing and fetch output data----- @http.route(['/somo_url'], type='json', auth="user", website=True) def input_data_processing(self, **kw): cr, context, pool, uid = request.cr, request.context, request.registry, request.uid #Fetch input json data sent from js input_data = kw.get('input_data') # Your code is here return { 'output_data' : output_data } Or return True # In case if we don’t want to return data |
Note: Type must be ‘json’ as parameters of the controller.
Step 4: Load script.js file in template.xml file. Refer below code for the same.
<template id="inherit_assets_frontend" name="web_example assets" inherit_id="website.assets_frontend"> <xpath expr="script[last()]" position="after"> <script type="text/javascript" src="/module_name/static/src/js/script.js"/> </xpath> </template> |
That’s all folks. You can use above code to implement JSON Web Controller in Odoo