Pass variable from JavaScript function to controller: Using JSQueryBuilder

425 views
Skip to first unread message

Madhavi

unread,
Sep 22, 2016, 8:49:47 AM9/22/16
to web2py-users

Hi,

 

I am trying to use JavaScript Query Builder plugin (querybuilder.js.org) with web2py. The plugin is installed successfully and I can see the querybuilder object in my view. I want to finally pass the string containing the filters selected from the view to another controller function for further processing. The code I am using on the view is below:

 

<button onclick='myFunction();'>Get rules</button>

<script>

    function myFunction();{

        var result = JSON.stringify($('#builder-basic').queryBuilder('getRules'), null, 2);

        ajax('{{=URL('default', 'showfilters', vars=dict(result=result))}}', [], ':eval');

    }

</script>

 

I want to pass ‘result’ variable to ‘showfilters’ controller function and call ‘showfilters’ view on clicking on ‘Get rules’ button. But the above code doesn’t work and gives this error:

<type 'exceptions.NameError'> name 'result' is not defined

I understand this could be because 'result' variable is not defined in my controller function corresponding to this view. What is the correct way to pass the value of a variable declared through Java Script to a controller function in web2py?

Please help me here – I am novice to both web2py and Java Script and have been struggling with this for quite some time. I would prefer to pass the variable result through dictionary and not as an argument, as it will contain spaces and special characters which I want to preserve in the string.

Thanks,

Madhavi

Anthony

unread,
Sep 22, 2016, 2:18:01 PM9/22/16
to web2py-users
"result" is a Javascript variable, so it does not exist in the Python context in which the URL() function is evaluated. Instead, you must add that part of the URL via Javascript:

ajax('{{=URL('default', 'showfilters')}}' + '?result=' + result, [], ':eval');

Anthony

Aydin

unread,
Jul 31, 2019, 9:32:40 PM7/31/19
to web2py-users
Anthony, how to pass multiple variables, say result1 and result2?

Paco Bernal

unread,
Aug 1, 2019, 5:24:33 PM8/1/19
to web...@googlegroups.com
Hi

ajax('{{=URL('default', 'showfilters')}}' + '?result1=' + result1 + '&result2='+result2, [], ':eval');

result1 = request.vars.result1
result2 = request.vars.result2

or

ajax('{{=URL('default', 'showfilters')}}/' + result1 + '/' + result2, [], ':eval');

result1 = request.args(0)
result2 = request.args(1)

You will need to take care about the strings you pass to the url or you will bad results back to the app.

ajax('{{=URL('default','save_user')}}/'+agent_id+'?first_name='+encodeURIComponent($('#first_name').val())+'&last_name='+encodeURIComponent($('#last_name').val())+'&email='+encodeURIComponent($('#email').val())+'&phone='+encodeURIComponent($('#phone').val()),[],':eval');

Regards
Reply all
Reply to author
Forward
0 new messages