Reputation: 907
I have a list of Projects in my view and I would like to dynamically generate individual pages for each one. My view:
{{for i in project_list:}}
<ul>
<input id="hello" type="hidden" value="{{response.write(i)}}" name="project_Name">
<li><a onclick="ajax('{{=URL('default', 'view_project')}}', ['project_Name'], 'target');">View Project</a></li>
</ul>
{{pass}}
My controller:
def view_project():
print request.vars.project_Name
return dict(name=request.vars.project_Name)
Essentially, I would like to identify each Project by its project_Name
.
This is the current output from the controller:
['Customizable logistical service-desk ', 'Extended contextually-based prod
uctivity ', 'Face-to-face modular circuit ', 'Multi-tiered stable intranet
', 'Quality-focused coherent budgetary management ']
Why am I receiving an Array of all project names as output? I just want to identify each project.
Any advice is appreciated!
Upvotes: 0
Views: 428
Reputation: 717
The web2py ajax function sends to the server the value of the html element with the name attribute passed in the functions second parameter ("project_Name" in your case), but if there are more than one field with the same name, it will send the values of all of them.
So, you are creating with a loop many fields with the same name, and the ajax function is sending all the values to the server.
You can solve the problem appending a count variable to each field name (and its name on his onclick attribute):
{{count = 1}}
{{for i in project_list:}}
<ul>
<input id="hello" type="hidden" value="{{response.write(i)}}" name="project_Name{{=count}}">
<li><a onclick="ajax('{{=URL('default', 'view_project')}}', ['project_Name{{=count}}'], 'target');">View Project</a></li>
</ul>
{{count += 1}}
{{pass}}
Or use a more clean solution usin the JQuery ajax function
Upvotes: 1
Reputation: 25536
You have:
ajax('{{=URL('default', 'view_project')}}', ['project_Name'], 'target')
You have specified "project_Name" as the form input element from which to extract the value to post. However, there are multiple inputs on the page all with that same name. As a result, the Ajax function serializes all of their values into a single list and posts the whole list.
You could give each input a unique name, but there is a simpler solution. It appears you are using the hidden input
elements merely to hold values to be sent by the Ajax function. There is no need for that -- instead, you can simply encode the values directly in the Ajax URL. So, get rid of the input
elements and change your ajax
call to:
ajax('{{=URL('default', 'view_project', vars=dict(project_name=i)}}', [], 'target')
Upvotes: 1