jsp jump url parameters' names are the html elements' names - javascript

I write web front page page.jsp:
<select id="type_label" name="type_label">
<option value=""></option>
<c:forEach items="${types}" var="type" varStatus="status">
<option value="${type}">${type}</option>
</c:forEach>
</select>
function dosearch(){
var type_label = document.getElementById("type_label");
var tagVal = type_label.options[type_label.selectedIndex].value;
window.location="${ctx}/content/query?tag="+tagVal;
}
In controller Controller.java:
I get the data rows of mysql and put these data rows in List list.
Then put the list in model:
model.add("list", list);
The list has data rows in my log.
Then the controller make the page jump to page.jsp.
The project use rose java web frame.
return "content/page";
It make the page jump to page.jsp.
But the url is:
http://127.0.0.1:3428/web/content/page?type_label=%E6%90%9E%E7%AC%91&currentPage=
The url is expected to be:
http://127.0.0.1:3428/web/content/page?tag=%E6%90%9E%E7%AC%91&currentPage=
The url's parameter is type_label and not tag.
But type_label is select html element's id.
Why?Please give me a hand.Thanks a lot!

I know the reason about it.
After dosearch() executed, got the list of the tag from mysql.
Then jumped to content/page.jsp by
return "content/page";
The page would load by the form:
<form action="${ctx}/content/page" method="get" name="Form" id="Form"
class="form-horizontal">
It would get data list from mysql again. Because it got tag parameter by the tag element's name "type_label".
Then its url was "..type_label=tagname". The controller's method didn't get tag parameter from "type_label". So it had no tag parameter now.
It would get data list without tag.
So the data list was not the data of this tag.
Solution:
The tag element in HTML is that:
<select id="tag" name="tag">
<option value=""></option>
<c:forEach items="${tag}" var="tag" varStatus="status">
<option value="${tag}">${tag}</option>
</c:forEach>
</select>
Modify the dosearch() method to this:
function dosearch(){
$("#form").submit();
}
And modify the controller code to get tag parameter. Like that:
#Get("page")
public String page(Model model, #Param("tag") String tag){
...
}
The controller will get tag parameter by the tag element's name "tag".
After dosearch() executed, the controller will get tag parameter from the form.
Then get the data list of this tag in controller. And add list to model.
At last the page will show the list of the tag.

Related

How to access the JavaScript variable in the python code in Web2py's view

I'm trying to store the value of the drop-down 'product' in a javaScript variable and then trying to use that variable in Python code in html view of Web2py framework to further create the drop down for the other component.
I tried two different ways, but both of them did not work.
I want to do a query on database using a keyword which is selected from the Product drop-down and hence generating the second drop down.
<script>
function run()
{
var e = document.getElementById('local_product');
var strUser = e.options[e.selectedIndex].text;
document.getElementById('div_release').innerHTML =' <label>Release : </label> {{rows1 = db(db.Builds.Build.like(\"}}strUser%{{\"")).select()}} <select> {{for r1 in rows1:}}<option>{{=r1.Build}}</option> {{pass}}</select>'
or
document.getElementById('div_release').innerHTML =' <label>Release: </label> {{rows2=db.executesql("Select Build from Builds where Build like\"request.vars.prod_tab\"" )}} <select> {{for r1 in rows2:}}<option>{{=r1}}</option> {{pass}}</select>'
}
</script>
<form method="POST" action="" name="product_filter">
<label>Product: </label>
<select id="local_product" onchange="run()" name=prod_tab >
{{ for r in product_list: }}
<option value="{{r}}">
{{=r}}
</option>
{{pass}}
</select>
{{pass}}
<input type="Submit" name=Set Value="Set">
<form>
Python code in web2py views is executed on the server before the page is sent to the browser, so it is not possible to execute any Python code within the browser in response to user actions. Instead, you must send an Ajax request to the server to retrieve additional data to inject in the page. For ideas on how to achieve what you want, see this answer.

MVC select model's data from javascript

I am passing a model IEnumerable to a view. Appending the model to a dropdownlist
#Html.DropDownList("ddlOffers", new SelectList(Model,"Id","Title"))
<p id="result"></p>
I have javascript on change I am getting value selected
<script>
$(function () {
$("#ddlOffers").change(function () {
alert(this.value);
});
});
</script>
It is retrieving the correct value Id. On selecting from the list I want grab the record details from a Model (such as Title,CreatedBy...etc) based on the selection.
How do I select the right data from the Model using value Id selected in the javascript? and should I then append the data to the p tag? Am I on the right track? Or is there a simpler solution?
Thanks for reading.
What #Html.DropDownList do is generate html like this:
<select id="ddlOffers" name="ddlOffers">
<option value="somevalue">sometext</option>
... for all your options
</select>
And if you just need the value selected, there's a shortcut in jquery:
<script>
$(function () {
$("#ddlOffers").change(function () {
alert($(this).val());
});
});
</script>
Or if you need anything other than the value, you can get the selected <option> itself by
<script>
$(function () {
$("#ddlOffers").change(function () {
console.log($(this).find("option:selected"));
console.log($("#ddlOffers option:selected")); //both of them do the same thing
});
});
</script>
suppose your model is
public class Model {
public int Id,
public string Title,
public int CreatedBy
/*Other Properties*/
}
when you put it through this statement
#Html.DropDownList("ddlOffers", new SelectList(Model,"Id","Title"))
All you get on the html side and you can check the source of the HTML file is
<select>
<option value="1">Title 1</option>
<option value="2">Title 2</option>
<option value="3">Title 3</option>
<option value="4">Title 4</option>
<option value="5">Title 5</option>
</select>
So you see the problem in getting other properties is that they dont exist in the HTML page and hence cannot be directly retrieved by the javascript.
What you can do instead is put all the data you need in the html attributes in the html option element by creating it manually.
#foreach(var m in Model)
{
#m.Title
}
now when you will handle the change even the data will be available inside the HTML and hence you will be able to access it. With something like this
<script>
$(function () {
$("#ddlOffers").change(function () {
var createdBy = $(this).data('createdBy');
alert(createdBy);
});
});
</script>
Alternatively what you can do is and this approach will only help you if you want to later convert this into a big application.
after selecting the value in the javascript you send a ajax request to another action on your server with will return you all the fields you need back.
Update:-
3. You can also inject the model serializing it to JSON in the view and then whenever required accessing the info using js. For this i generally use Newtonsoft Json (install-package newtonsoft.json) then inside the view do something like this
<script>
var model = #JsonConvert.SerializeObject(Model);
</script>
The way I have approached this before is to use a form like this:
#using (Ajax.BeginForm("ActionName", "ControllerName",new AjaxOptions{HttpMethod = "POST"}))
{
#Html.DropDownList("ddlOffers", new SelectList(Model,"Id","Title"))
<button type="submit">Submit</button>
}
Have the form submit to a controller and dropdown's value set to your ID field and then when it posts back into the controller, get the full object based on ID

included php cannot access form on the page

I have some html code used in more than one place, I put it in a .php file and include it where needed. In one case I include this code inside a form.
This form has one element; and just below that, inside the form, is the include for the php file that has the html code.
I find that the included html from the .php file cannot access the form element but the one element that is on the same page as the form has no such trouble.
Here's the included code that's in a separate .PHP file:
// inside theIncluded.php
<div id="aDivToBeIncluded">Testing</div>
And here is my form declaration -- the signature looks overly complex because I removed other elements (text boxes, etc) for this explanation:
<form style="display: inline-block" name="areaComboboxForm" method="post"
autocomplete="off" enctype="multipart/form-data">
<select name="mySelect" id="mySelectId" onchange="return doChange(this)" >
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<?php require_once("theIncluded.php") ?>
</form>
And here is the troublesome code:
function doChange(theSelect)
{
var theSelect = document.getElementById('mySelectId');
// THIS REPORTS THAT THE FORM IS 'objectHTMLFormElement'
alert("doChange(), the form is: " + theSelect.form);
var theIncludedDiv= document.getElementById('aDivToBeIncluded');
// THIS REPORTS THAT theIncludedDiv IS 'objectHTMLDivElement'
alert("doChange(), the included Div is: " + theIncludedDiv);
// THIS REPORTS THAT theIncludedDiv.form IS 'undefined'
alert("doChange(), the form is: " + theIncludedDiv.form);
}
To recap, I include some html code from a .php file that has one DOM element, a div.
That div, when accessed on the page where its .php file is included, resolves to an
objectHTMLDivElement.
But when I try to access the .form that the objectHTMLDivElement is included on -- the form is 'undefined.'
Is there a reason for this? All this code is in the same folder on the same webserver, a localhost XAMPP web server.
According to your code, the div is inside the form and has no .form of its own.
You'd be looking for theIncludedDiv.parentNode if you wanted the form element.
.form is only a property of HTMLInputElements in HTML4 and in HTML5 it has some different behavior(it can be the id of the form element or null).

how can i implement a onclick in scriptlet?

I want to check which value I selected in a scriplet, when I press some value in the drop down list. How can I do that?
I tried as follows : ( below two codes are in the same page "test.jsp" )
code : for list
<select id="stream" name="current_session" onclick="fun2()" >
<option value="Winter">Winter</option>
<option value="Monsoon">Monsoon</option>
</select>
code : scriplet inside a javascript ( note that both html, scriplet are in the same page )
<script>
function fun2(){
<%
String given_session=request.getParameter("stream");
system.out.println(given_session);
%>
}
note : I am getting output as null, instead of selected session value. So how can get the selected values in scriplet which is in the same jsp page?
you can use a js to select the value
function get_the_value(){
var e = document.getElementById('stream').value;
return e;
}
In your web browser you have only html, javascript and css. All JSP code is meant to be run on the server. So you get only the output of the jsp file. And after this you cannot change the jsp code.

Display form result on same page using php with smarty

My web app is integrated to facebook. I created a form in tpl file with only has one input, which is select input. User has to choose one of his facebook group. The value of the option is id of each group.
So this is what i would like to do :
When user change the option (onchange), list of members of the selected group will appear bellow the select div. I don't know what i should use (javascript, jquery, ajax, etc) and how to implement it in my code.
Here my code snippet :
{* --- form in tpl file --- *}
<form method="post">
<fieldset>
<div class="row">
<p style="font-weight:bold;">Choose your facebook group :</p>
</div>
<div class="row">
<select name="group" onchange="idontknow">
{foreach from=$userGroupsData item=group}
<option value="{$group.id}">{$group.name}</option>
{/foreach}
</select>
</div>
<div class="row">
{* the place where members list will appear *}
</div>
</fieldset>
</form>
PHP code to retrieve member list of selected group (if I use submit method) :
<?php
$groupId = $_POST['group'];
$groupmember = $facebook->api('/'.$groupId.'/members');
$membergroup = $groupmember['data'];
foreach ($membergroup as $membergroups) {
echo "<li>".$membergroups['name']."</li>";
}
?>
Any help would be greatly appreciated. Thank you
I would make an Ajax request using jQuery:
$(function() {
$('body').on('change', 'select[name="group"]', function() {
var groupId = $(this).val();
$.post('path/to/your/script', groupId)
.done(function(data) {
$('form .row').html(data);
});
});
});
If it were me, I would have the backend return JSON data instead of HTML and I would build the HTML dynamically in the Ajax callback.
Also, this scenario is one of the many reasons I prefer to use MVC architecture on the backend. If you were using an MVC framework like say CodeIgniter for example, the URL you're posting the data to would take care of the routing like this:
MVC-style URL = 'mycontroller/mymethod/myparam'.
In this example, mycontroller would be the class (script) you're calling, mymethod would be the specific function you want to call in the controller, and myparam would be the data you're passing to that function.

Categories