1

I am trying to write a jQuery even that inserts an entry into a table like this:

 $('#insertButton').on('click',function(){
        {{db.myTable.insert(user_id=auth.user_id, text=myText)}}
  });

As a real general example of what I am trying to do. It's located in the block of my The problem is that when the view is loaded the function fires automatically. It does that insert every time the page is loaded. Is there some quirk of web2py that doesn't let you have python code embedded in your jQuery events? Is there a way around this?

1
  • Don't mix things up. Python is for the server-side only. jQuery is for client-side only. Commented Jul 12, 2013 at 17:34

1 Answer 1

1

In web2py templates, all of the Python code is executed on the server when the page is first generated. The line:

{{db.myTable.insert(user_id=auth.user_id, text=myText)}}

does not start with an =, so it does not write anything into the HTML response. Instead, it simply executes that Python code on the server. You cannot simply embed Python in your Javascript -- the browser wouldn't know what to do with it.

If you want to use Javascript to trigger an insert on the server, you'll have to do it via an Ajax call to an action that handles the insert. See here as well as documentation on the jQuery .ajax method.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok this is really confusing documentation but I think I am starting to see how I would use this. Thank you.
Hey @Anthony, I was trying to use the URL helper in one of the javascript files that is included in layout.html, but it takes it as a string instead of evaluating it. Should I write the same js code as inline js in layout.html it works perfectly fine. Any workaround or a conventional way to use that in static js files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.