Search code examples
javascriptpython-2.7controllerodoo-10

How to call Python Controller function in Javascript Odoo 10


I am new with this technology. Please bear with me :) Thank you

Do you have any idea on how to call a python controller function using javascript? I always get cross-origin-browser error. So I tried this,

.py

@http.route('/custom/createdb', type='json', auth="public", methods=["POST"], website=True)
    def createdb(self, db_name):
    
        session = self._authenticate()
        if not session:
            return json.dumps(False)

        # create a new database
        headers = {'Content-Type': 'application/json'}
        
        create_db_url = "http://localhost:8090/custom_api/create_db"
        data = {"jsonrpc": 2.0, "params": { "name": db_name } }

        _logger.debug("Creating database...")
        r = session.post(url=create_db_url, data=json.dumps(data), headers=headers)

        if r.ok:
            return json.dumps(True)
        else:
            return json.dumps(False)

.js

var session = require('web.session');

$(function()
    {
        $("#start_trial").click(function()
        {
            session.rpc('/custom/createdb', 
                {
                    // how to get data here
                }).then(function (result) 
                {
                    // result
                    
                });
        });
    });

Solution

  • just solved my own question.

    var db_name = $("input[name='partner_name']").val();
    
    session.rpc('/custom/createdb', {
                db_name : db_name
            }).then(function() {
                console.log("Creating database");
            }, function () {
                console.log("calling /custom/createdb caused an exception!");
            });
    

    I just followed this documentation: https://www.odoo.com/documentation/10.0/reference/javascript.html#low-level-api-rpc-calls-to-python-side