controller not returning java script variable correctly

62 views
Skip to first unread message

jonas

unread,
Jan 15, 2014, 11:09:04 AM1/15/14
to web...@googlegroups.com
Hi

I have a controller that is supposed to return a list to a js function (for testing purposes):

def test():

    print "called2"

    data=[3, 6, 2, 7, 5, 2, 0, 3, 8, 9, 2, 5, 9, 3, 6, 3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 2, 7]
 
   return 'var data=%s;' % data 

I am calling this with an ajax function:

<script>
 ajax('{{=URL('test')}}',[],':eval');
 document.write(data);
 </script>

but is seems that the data is not present in the script.

what went wrong? 

Anthony

unread,
Jan 15, 2014, 11:38:46 AM1/15/14
to web...@googlegroups.com
Javascript is asynchronous -- the document.write() line will be executed before the ajax call has completed. Try putting the document.write() in the returned Javascript itself.

Jonas Fredriksson

unread,
Jan 15, 2014, 12:59:46 PM1/15/14
to web...@googlegroups.com
ok, now I undestand what you mean:


def test():

    print "called2"
    data3=[3, 6, 2, 7, 5, 2, 0, 3, 8, 9, 2, 5, 9, 3, 6, 3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 2, 7]

    return 'graph1(%s);' % data3   

<script>
 ajax('{{=URL('test')}}',[],':eval');
 </script>

graph1 is the actual function, the write function was just for testing. This works but it means that I have to make a python function for every js function call when passing values from python functions.



--
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/WQ3geDp_pEo/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/groups/opt_out.

Anthony

unread,
Jan 15, 2014, 1:34:32 PM1/15/14
to web...@googlegroups.com
graph1 is the actual function, the write function was just for testing. This works but it means that I have to make a python function for every js function call when passing values from python functions.

You can do this:

def test():
    data
= ...
   
return '%s(%s);' % (request.args(0), data)
 
<script>
 ajax
('{{=URL('default', 'test', args='myjsfunction')}}', [], ':eval');
</script>

Just pass the name of the JS function in the URL.

Anthony

Jonas Fredriksson

unread,
Jan 15, 2014, 2:48:41 PM1/15/14
to web...@googlegroups.com
nice solution and it works.

thanks


--
Reply all
Reply to author
Forward
0 new messages