Search code examples
javascriptpythonsqliteweb2pyweb2py-modules

storing elements in a database by using JavaScript in web2py


The first thing that I would like to point out is that I am like a nervous programmer or nervous learner. I feel like I want to learn things fast, so I start checking websites and books very quickly and If I feel like what I am reading doesn't satisfy my need then I just close it and start doing something else. I am just wondering if that kind of behavior sounds familiar to you.

I have the following problem. I am just starting to learn how to program in web2py and I need to store javascript input in a sqlite database, so for example I have the following table:

db = DAL ('sqlite://storage.sqlite')
db.define_table('company', Field('name', notnull = True, unique = True), format = '%(name)s')
db.define_table(
   'contact',
   Field('name', notnull = True),
   format = '%(name)s'
)

and I have the following script code

li.innerHTML = document.getElementById('task').value;

so I need to store that document.getElementById in the database. Can u point out the topics that I need to study in order to accomplish such task?


Solution

  • Start by reading the jQuery and Ajax chapter of the documentation. In particular, check out the ajax function.

    If the task element is a form element with a "name" attribute, you can call the ajax function as follows (assuming the name of the form element is "task"):

    ajax("{{=URL('default', 'insert_task')}}", ['task']);
    

    If the task element is not a form element, you can instead pass it to web2py via the query string:

    ajax("{{=URL('default', 'insert_task')}}" + '?task=' + encodeURIComponent(li.innerHTML));
    

    Then in the web2py controller, the insert_task action would handle the insert:

    def insert_task():
        db.mytable.insert(task=request.vars.task)
        return 'Success'
    

    Note, the ajax function takes a third argument, which can be (a) the id of an HTML element where the returned value should be inserted, (b) a Javascript function to which the returned value will be passed, or (c) the string ":eval", which will result in the returned value being interpreted as Javascript and evaluated. You can use this argument if you want to display some message on the page or make some change to the display after the insert has completed.

    Finally, if the ajax function is not adequate for your needs, you can always use jQuery's Ajax facilities, or any other Javascript method of making Ajax calls.