Pass multiple arguments to URL through javascript

6,083 views
Skip to first unread message

Vineet

unread,
Dec 3, 2011, 11:10:59 AM12/3/11
to web2py-users
I referred to the below-mentioned thread (but could not reply to it).

https://groups.google.com/group/web2py/browse_thread/thread/61d57e887e42aee8/c3dd5cd43b9d5527?lnk=gst&q=URL+javascript+variable

My question is ---
If I have two javascript variables, which are to be passed to a
controller through URL helper as under --

[CODE]
<script>
....
var param1 = 'value1' ;
var param2 = 'value2'

.... "{{URL(r=request,c='static',f='action')}}/"+param1&param2
that did not work
.... "{{URL(r=request,c='static',f='action')}}/"+(param1,param2)
didn't work either.
.....
</script>
[/CODE]

How do I code it?


Thanks,
Vineet

Anthony

unread,
Dec 3, 2011, 11:37:58 AM12/3/11
to web...@googlegroups.com

<script>
  ....
 var param1 = 'value1' ;
 var param2 = 'value2'

 .... "{{URL(r=request,c='static',f='action')}}/"+param1&param2

You need to use "=" to write the output of URL.

{{=URL(...)}} + '/' + param1 + '/' + param2

Anthony

lyn2py

unread,
Dec 3, 2011, 3:48:06 PM12/3/11
to web2py-users
You can try: {{URL('static','action',args=[param1,param2])}}

On Dec 4, 12:10 am, Vineet <vineet.deod...@gmail.com> wrote:
> I referred to the below-mentioned thread (but could not reply to it).
>

> https://groups.google.com/group/web2py/browse_thread/thread/61d57e887...

Anthony

unread,
Dec 3, 2011, 4:02:32 PM12/3/11
to web...@googlegroups.com
On Saturday, December 3, 2011 3:48:06 PM UTC-5, lyn2py wrote:
You can try: {{URL('static','action',args=[param1,param2])}}

No, param1 and param2 are Javascript variables set on the client side, but the URL function is called on the server side before the page is delivered. So, param1 and param2 have to be added to the output of URL() via Javascript.

Anthony

Brian M

unread,
Dec 3, 2011, 5:53:06 PM12/3/11
to web...@googlegroups.com
I've used a jQuery plugin called jQuery.query that can manipulate URLs.  If memory serves correct you do something along the lines of $.query.set('var', value) to set querystring values. And $.query.get('var') to retrieve.

Sadly the jQuery team seems to have taken down the jQuery plugins site and I can't seem to find any other links to the source. Even the author's site just links back to the jQuery plugins site :\  I might be able to dig up a copy to send you if you're interested.

~Brian
Message has been deleted
Message has been deleted

Vineet

unread,
Dec 4, 2011, 2:32:54 AM12/4/11
to web2py-users
@Anthony, thanks. Your method worked.
Secondly, if I want to pass arguments by name, would it be okay to do
something like this---->>

{{=URL(...)}} + '/' + 'p1=' + param1 + '/' + 'p2=' + param2

@Brian, I would be interested & grateful to you if you can send me a
copy of jQuery.query
(as mentioned by you). Thanks

---Vineet

On Dec 4, 3:53 am, Brian M <bmere...@gmail.com> wrote:
> I've used a jQuery plugin called jQuery.query that can manipulate URLs.  If
> memory serves correct you do something along the lines of
> $.query.set('var', value) to set querystring values. And $.query.get('var')
> to retrieve.
>
> Sadly the jQuery team seems to have taken down the jQuery plugins site and

> I can't seem to find any other links to the source. Even the author's site<http://blairmitchelmore.com/jquery>just links back to the jQuery plugins site :\  I might be able to dig up a

Jonathan Lundell

unread,
Dec 4, 2011, 3:14:25 AM12/4/11
to web...@googlegroups.com
On Dec 3, 2011, at 11:32 PM, Vineet wrote:

> @Anthony, thanks. Your method worked.
> Secondly, if I want to pass arguments by name, would it be okay to do
> something like this---->>
>
> {{=URL(...)}} + '/' + 'p1=' + param1 + '/' + 'p2=' + param2

Almost. You want:

{{=URL(...)}} + '?p1=' + param1 + '&p2=' + param2

...then look for p1 & p2 in request.vars.

Massimo Di Pierro

unread,
Dec 4, 2011, 1:33:14 PM12/4/11
to web2py-users
what's wrong with?

{{=URL(...,vars=dict(p1=param1,p2=param2))}}

Massimo Di Pierro

unread,
Dec 4, 2011, 1:33:39 PM12/4/11
to web2py-users
Ignore my comment... I missed the context.

On Dec 4, 12:33 pm, Massimo Di Pierro <massimo.dipie...@gmail.com>
wrote:

Brian M

unread,
Dec 4, 2011, 8:16:40 PM12/4/11
to web...@googlegroups.com
Vineet,

My copy of jQuery.query.js is attached - I'm assuming since it's released under the WTFPL the author won't mind :D

You may also want to look at these:
http://stackoverflow.com/questions/2053157/how-to-use-jquery-to-manipulate-the-querystring
http://stackoverflow.com/questions/4344405/jquery-url-builder-parser
http://stackoverflow.com/questions/1090948/change-url-parameters-with-jquery

Brian
jquery.query.js

Vineet

unread,
Dec 6, 2011, 11:12:13 AM12/6/11
to web2py-users
@Brian,
Thanks. I will experiment with this plugin.
Looks like very interesting stuff.

--- Vineet

On Dec 5, 6:16 am, Brian M <bmere...@gmail.com> wrote:
> Vineet,
>
> My copy of jQuery.query.js is attached - I'm assuming since it's released
> under the WTFPL the author won't mind :D
>

> You may also want to look at these:http://stackoverflow.com/questions/2053157/how-to-use-jquery-to-manip...http://stackoverflow.com/questions/4344405/jquery-url-builder-parserhttp://stackoverflow.com/questions/1090948/change-url-parameters-with...
>
> Brian
>
>  jquery.query.js
> 7KViewDownload

Ashraf Mansour

unread,
May 20, 2012, 1:00:27 PM5/20/12
to web...@googlegroups.com
I think this is an important topic, And needs to be highlighted in the book and by example.

Ashraf Mansour

unread,
May 20, 2012, 1:18:44 PM5/20/12
to web...@googlegroups.com
I tried this

<h3   {{=A('  ..... ',_href=URL('action'))}}/param1/param2 </h3>

and it did not work.:)

what is the right way of doing it?

Bruce Wade

unread,
May 20, 2012, 1:59:01 PM5/20/12
to web...@googlegroups.com

{{=URL('controller','action', args=[arg1, arg2])}}

Anthony

unread,
May 20, 2012, 3:05:10 PM5/20/12
to web...@googlegroups.com
On Sunday, May 20, 2012 1:18:44 PM UTC-4, Ashraf Mansour wrote:
I tried this

<h3   {{=A('  ..... ',_href=URL('action'))}}/param1/param2 </h3>

and it did not work.:)

what is the right way of doing it?

A() doesn't produce a URL -- it produces an anchor tag (i.e., <a href="...">...</a>), to which you are then appending "/param1/param2", which obviously doesn't work.

What are you trying to do? Are param1 and param2 known on the server side? If so, add them as args to the URL() function. If they are determined on the client side, then you'll need to use Javascript to generate the URL on the client.

Anthony

Ashraf Mansour

unread,
May 20, 2012, 3:43:38 PM5/20/12
to web...@googlegroups.com
thanks for the immediate reply.

param1 and param2 are determined on the client side.

how can it be generated by javascript?

Ashraf Mansour

unread,
May 20, 2012, 3:48:02 PM5/20/12
to web...@googlegroups.com
thanks for the immediate reply.

param1 and param2 are determined on the client side.

<h3   {{=A('  ..... ',_href=URL('action'))}}/param1/param2 </h3> 

Anthony

unread,
May 20, 2012, 7:36:54 PM5/20/12
to web...@googlegroups.com


On Sunday, May 20, 2012 3:43:38 PM UTC-4, Ashraf Mansour wrote:
thanks for the immediate reply.

param1 and param2 are determined on the client side.

how can it be generated by javascript?


It depends. Here's one example:

<script>
jQuery
(function() {
 
var param1 = 'hello'
 
var param2 = 'world'
  jQuery
('a#mylink').attr('href', '{{=URL("action")}}' + '/' + param1 + '/' + param2);
});
</script>

<h3>{{=A('...', _href='', _id='mylink')}}</h3>

When the page is loaded, the href of the mylink anchor tag will be replaced with the "action" URL along with the values of param1 and param2 appended. Of course, you'll need some way to set the values of param1 and param2, and there may be some other event that should trigger the replacement -- it depends what you're trying to do.

Anthony

Bruce Wade

unread,
May 20, 2012, 7:57:10 PM5/20/12
to web...@googlegroups.com
Why would you do the code like that??
Updated:
<script>
jQuery
(function() {
 
var param1 = 'hello'
 
var param2 = 'world'

  jQuery
('a#mylink').attr('href', '{{=URL("action", args=["' + param1 + '","' + param2 + '"])}}');

});
</script>

<h3>{{=A('...', _href='', _id='mylink')}}</h3>
--
--
Regards,
Bruce Wade
http://ca.linkedin.com/in/brucelwade
http://www.wadecybertech.com
35E.gif

Anthony

unread,
May 20, 2012, 8:19:45 PM5/20/12
to web...@googlegroups.com
He said param1 and param2 are determined on the client side -- which means they cannot be set on the server side by web2py. Of course, I don't know what he's actually doing on the client side, so this exact code may or may not be relevant. Do you have an alternative suggestion?

Anthony

Bruce Wade

unread,
May 20, 2012, 8:56:51 PM5/20/12
to web...@googlegroups.com
Well honestly if it was a dynamic link I wouldn't even use URL as good style of JS programming is putting the code in a .js if this is the case then the web2py parser cannot even access the URL to parse it. (At least I have never been successful with that process.)

If they are getting the params at a later time and in a js file there is no need in using the URL just use url = '/path/' + param + '/' + param; The only problem with this is if he changes the path, however if he changes the path he would be required to update URL() anyways.

I have fell into the trap on trying to rely on the helpers to much myself in the past. Some places in your code you shouldn't use them. Trying to use them for everything kind of forces you to change your logic to bend around web2py instead of having web2py work with your logic. Also whenever you use URL instead of the direct url='/path' the framework is forced to do more function calls, in some situations like this one it isn't really worth having the extra function call and it is actually more typing :D

Ashraf Mansour

unread,
May 20, 2012, 10:09:52 PM5/20/12
to web...@googlegroups.com
thank you for your interest.

let me brief what i am doing. I am building an application accessing google maps api v3. I need the function that decide if a certain point is within certain bounds. my understanding is that i need to do that in the view ( by passing the point and the coordinates of the bounds ). the view js can access them if they in {{ }}. then I need to return the output of the function to the next action, by clicking 

<h3   {{=A('  ..... ',_href=URL('action'))}}/param1/param2 </h3>  

it did not work (it does not write the values of param1 and param2 )

and 

<h3   {{=A('  ..... ',_href=URL('action',args=[param1,param2]))}} </h3>   

is not working ( param1, param2 is not defind within {{ }}  )


is there a solution without using jquery?

Bruce Wade

unread,
May 20, 2012, 10:15:45 PM5/20/12
to web...@googlegroups.com
You do realise that you are missing the closing >?


<h3   {{=A('  ..... ',_href=URL('action'))}}/
param1/param2 </h3>

Also what you are trying to do in this code will never work.

<h3   {{=A('  ..... ',_href=URL('action'))}}/
param1/param2 </h3>

becomes

<h3 <a href='/action'>....</a>/param1/param2 </h3>

Try this:

<h3><a href="{{=URL('action')}}/param1/param2">....</a></h3>

Anthony

unread,
May 20, 2012, 10:38:04 PM5/20/12
to web...@googlegroups.com
I wasn't suggesting he should use the URL() function, just pointing out that it can't be used to build a URL on the client side, and showing a simple example of how to build a URL on the client side via Javascript (use of the URL() function was incidental and not central to the point of the example). In any given case, it may or may not make sense to use the URL() function to build the base URL (vs. hard-coding it in a .js file), and I wouldn't state a blanket rule either way (if you're using the web2py rewrite system, it's generally a good idea to use URL() whenever feasible).

Also, I hadn't realized you made an update to my code example. The update wouldn't work because it attempts to put Javascript variables inside Python code that must be executed on the server.

Anthony

Ashraf Mansour

unread,
May 20, 2012, 10:41:35 PM5/20/12
to web...@googlegroups.com
both

<h3><a href="{{=URL('action')}}/param1/param2">....</a></h3> 

and

<h3><a href={{=URL('action')}}/param1/param2>....</a></h3> 


are not working ( they are not showing the values of param1 and param2 )


Anthony

unread,
May 20, 2012, 10:46:20 PM5/20/12
to web...@googlegroups.com
let me brief what i am doing. I am building an application accessing google maps api v3. I need the function that decide if a certain point is within certain bounds. my understanding is that i need to do that in the view ( by passing the point and the coordinates of the bounds ). the view js can access them if they in {{ }}. 

What do you mean by needing to do that "in the view"? Do you mean in the browser? If so, that's not the same thing as "in the view". In web2py, the view is a special template that can include Python code. The view is executed on the server, and the output of that execution is what is sent to the browser. The browser does not see any of the Python code (i.e., none of the {{...}} end up in the browser).

is there a solution without using jquery?

It's still not clear what you are doing. What are param1 and param2? Are they determined dynamically within the browser? If so, you'll need Javascript to build the URL in the browser (it doesn't have to be jQuery specifically, but some form of Javascript). If param1 and param2 are known on the server at the time the page is being constructed by web2py, then you can simply include them as args in the call to the URL() function.

Anthony 

Anthony

unread,
May 20, 2012, 10:49:17 PM5/20/12
to web...@googlegroups.com
You are simply putting the literal strings "param1" and "param2" directly into your HTML there, so of course the values of those variables won't be shown. What are param1 and param2? Are they Javascript variables? If so, where are they defined? If they are Javascript variables, then you have to use Javascript to build the URL -- you cannot just paste Javascript variables directly into HTML and have the browser translate them into their values.

Anthony

Bruce Wade

unread,
May 20, 2012, 10:49:24 PM5/20/12
to web...@googlegroups.com
If param1 and param2 are from javascript:

1) You can not write the code in headers as you have current written you will have to use something like the following:
<h3><a id='url_with_params'>....</a></h3>

// javascript function:
function generateURL(param1, param2) {
   url = '/action/' + param1 + "/" + param2;
   $("url_with_params").attr('href', url);
Message has been deleted
Message has been deleted
Message has been deleted

Brian M

unread,
Sep 22, 2012, 9:12:04 PM9/22/12
to
Try this it'll give you a form, intercept the form submission and instead do an ajax call to the validate page which checks the email and password and if that's correct will return True and the page will get forwarded via JS to the next page with your email & password in the URL as args.

Why do the redirect via javascript rather than just having the controller do the redirect though?

Controller (default.py)
---------------------------------------------------------
def index():
   
"""
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html
    """

    response
.title = "Passing Args to URL through JS"
    response
.subtitle = T('Home')
    form
= SQLFORM.factory(
       
Field('email', 'string', requires=IS_NOT_EMPTY(IS_EMAIL())),
       
Field('password', 'string', requires=IS_NOT_EMPTY()),
        _name
='foo_form', _id='foo_form')
   
return dict(message=T('Demo'), form = form)

def validate():
   
import gluon.contrib.simplejson as sj
   
try:
       
if request.vars.email == 'm...@email.com' and request.vars.password == 'mypassword':
           
#success
           
return sj.dumps(dict(success=True, message='Success!'))
       
else:
           
#fail
           
return sj.dumps(dict(error=True, message='Oops wrong login info!'))
   
except:
       
#fail
       
return sj.dumps(dict(error=True, message='Login Failed, Please Try Again!'))
       
def receiving_page():
    response
.title = "Passing Args to URL through JS"
    response
.subtitle = T('Results')
   
#get passed args
    email
= request.args[0]
    password
= request.args[1]
   
return dict(email = email, password = password)



View (default/index.html)
----------------------------------------------------
{{left_sidebar_enabled=right_sidebar_enabled=False}}
{{extend 'layout.html'}}


<h1>{{=message}}</h1>

{{=form}}
<div id="status">Please Login</div>
<script type="text/
javascript">

$(function() {
     
   
    $('#foo_form').bind('submit',function(event){


 var email = $('#no_table_email').val();
  var password = $('#no_table_password').val();
  alert("
Submitting "+email+" "+password);
   
       $.post('{{=URL(r=request, f="
validate")}}',
        $(this).serialize(),
        function(json) {
           
            if(json.error) {
                //alert(json.message);
                $('#status').html(json.message);
            } else {
                //alert(json.message);
                $('#status').html(json.message);
                destination ='{{=URL(r=request, f="
receiving_page")}}/'+email +'/'+password;        
                //alert(destination);
                parent.window.location = destination;        
}
}, 'json');
return false;
});
});



</script>



{{block left_sidebar}}New Left Sidebar Content{{end}}
{{block right_sidebar}}New Right Sidebar Content{{end}}



-----------------------------

Good Luck!
~Brian

On Friday, September 21, 2012 11:20:44 AM UTC-5, jjcurats wrote:
good day great folks..i've been encountering same problem here..i have  2 variables in my function to pass in my controller...i just cant do it right trying lot of options already..here's my code:    

$(function() {
     
   
    $('#client-login').bind('submit',function(event){

 var email = $('#email').val(); 
  var password = $('#password').val();
    
       $.post('{{ constant('BB_URL_API') }}guest/client/login',
        $(this).serialize(),
        function(json) {
            if(json.error) {
                alert(json.error.message);
            } else {
                parent.window.location ='http://localhost/course_booking/index.php/display/client_info/'+email +password;            //this doesnt work...what is the right approach in this,,pls help

}
}, 'json');
return false;
});
});

and how should my controller look...?thanks people
Reply all
Reply to author
Forward
0 new messages