Controller to Ajax Function AND View

38 views
Skip to first unread message

Gualter Portella

unread,
May 17, 2018, 2:52:58 PM5/17/18
to web2py-users
Hi everyone,

I currently have a function in the default.py controller like the one below:

def overview():

    some code goes here
   
    return dict(income=json(income), form=form, bank=bank)


The first  variable is passed to the javascript tag in order to render a chart trough Chart.js

The last two variables are passed to the body of the view in order to render a form and generate a bank integer argument to redirect to a different controller/function upon clicking on an <a> tag.

As it is, everything is working great.

I was just wondering whether there is a way to make the first variable be retrieved by an AJAX function while the two others be sent to the view.

I can do it by creating two functions like these, but I need everything in the same controller:

def json_function():
     some code here
     
     return response.json(income)


def overview():

    some code goes here
   
    return dict(form=form, bank=bank)
    
   
Can I write these actions in just one controller?

My intention is to update the chart through an Ajax call without refreshing the page.

Many thanks.

Cheers,

Anthony

unread,
May 17, 2018, 4:08:47 PM5/17/18
to web2py-users
If you just want to avoid duplicating code to create the "income" variable, you could simply extract that into a separate function and call it from within each of the two controller actions. If you really want to have a single controller action for both the initial full page load and for subsequent Ajax updates, you can do something like this:

def overview():
    income
= [some code]
   
if request.ajax:
       
return response.json(income)
   
[more code]
   
return dict(income=json(income), form=form, bank=bank)

Anthony

Gualter Portella

unread,
May 18, 2018, 5:37:31 AM5/18/18
to web...@googlegroups.com
Great, Anthony.

I will give it a try and let you know the result.

Thanks.

Enviado do meu iPhone
--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to a topic in the Google Groups "web2py-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/web2py/YslNOw2O93U/unsubscribe.
To unsubscribe from this group and all its topics, send an email to web2py+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages