Passing argument of javascript function to java code - javascript

I am creating a GUI using dojo slider. Beside the slider there is a text box which will be used to display the current value of the slider.
What I want is that each time the slider is slided, the current value of the slider appears on the text box. Next, this value will be used in further calculation and the result will be displayed on another textbox.
What I have been doing is: inside the dojo slider, I call a javascript function which passes the current value of the slider.
Inside the javascript function, I want to pass the argument of the function into a java code inside the function. The argument will be used by the java code to do a calculation.
My problem is that I could not pass the argument to the java code. My question is how can I do that?
Below is the coding I have written:
<head>
<script type="text/javascript">
dojo.require("dijit.form.Slider");
dojo.require("dijit.form.TextBox");
dojo.ready(function(){
var slider = new dijit.form.HorizontalSlider({
name: "slider",
value: dojo.byId("walluvalueinit").value,
minimum: 0,
maximum: 1,
discreteValues:11,
intermediateChanges: true,
style: "width:300px;",
onChange: function(value){
dojo.byId("walluvalue").value = value;
changewalluvalue(value); //CALLING FUNCTION changewalluvalue()
}
}, "slider");
});
</script>
</head>
<body class="claro">
<jsp:useBean id="beanAnalysis" class="bean.Analysis" scope="application"/>
<script>
function changewalluvalue(value){
<%
ExteriorUnheatedGroundLossCalculation eug = new ExteriorUnheatedGroundLossCalculation();
//MORE CALCULATIONS
//SET U VALUES PROPERTY IN ExteriorUnheatedGroundLossCalculation
eug.setWallUValue(value); //THE ARGUMENT "value" SHOULD BE PASSED HERE
====more java code=====
%>
}
</script>
<form id="form1" name="form1" method="post" action="">
<tr>
<td width="150">Wall U Value</td>
<td width="411" align="center" valign="middle"><div id="slider"></div></td>
<td width="154" align="center" valign="middle"><label for="walluvalueinit"></label>
<input type="text" name="walluvalueinit" id="walluvalueinit" value="${beanAnalysis.wallUValue}"/></td>
<td width="152" align="center" valign="middle"><label for="walluvalue"></label>
<input type="text" name="walluvalue" id="walluvalue" /></td>
</tr>
<td colspan="2" align="center">Transmission Loss</td>
<td align="center" valign="middle"><label for="transmissionlossinit"></label>
<input type="text" name="transmissionlossinit" id="transmissionlossinit" value="${beanAnalysis.transmissionLoss}"/></td>
<td align="center" valign="middle"><label for="transmissionloss"></label>
<%--CALCULATION RESULT WILL BE DISPLAYED HERE--%>
<input type="text" name="transmissionloss" id="transmissionloss" /></td>
</form>
</body>

It's likely you'll need to use AJAX to pass the value to your Java code. I guess Dojo has some utilities for that. You'll also need to instrument your Java code to deal with the requests and to perform the actual logic.

It won't work because client-side JavaScript in a JSP cannot call server side Java methods. You have two options: (1) implement your calculation in JavaScript instead, or (2) do an Ajax call to a server-side service that performs the calculation.

Your calculation code should be a regular servlet, designed specifically to do the logic/calculations you require. JSP pages are best for providing HTML and/or direct renderable content.
Remember, once the page is served, any javascript on the page is executed on the client/browser. You no longer have direct access to Java structures. You must use AJAX to communicate back to the server. Have the servlet you invoke return a JSON object containing the results of the calculation.
On the client-side, use dojo.xhr (Get or Post version) and set the handleAs property to 'json'. For example:
dojo.xhrGet({
// URL to servlet that will do computation for us on the server
url: url_to_calc_servlet,
// Tell Dojo to handle return value as a JSON string, so dojo will
// auto-convert it into an Object.
handleAs: 'json',
// Specify request parameters to servlet as an object of
// name/value pairs.
content: {
sliderValue: XXX
},
// Define callback function for dojo to call when servlet returns
load: function(response) {
// response will be the object your servlet returned
// ... access response data and update page accordingly...
}
});
Check the Dojo documentation for more information about dojo.xhr.

Related

Using variable in Javascript to add functionality within cfml tags that call a query

I am looking to use my values from addition and subtraction, from javascript, and use them to increment the startRow and endRow values together. I have the addition and subtraction working, and the value being displayed. Now I cannot figure out how to add the value within the quotes. every time I try to use the ## variable markers, it tells me that my variables do not exist. I want to be able to press the next and Previous button and have it show me the former and latter 20 results. `
<cfoutput>
<script type="text/javascript">
var currentValue = 0;
var add = function(valueToAdd){
("adding: " + valueToAdd);
currentValue += valueToAdd;
document.getElementById('number').innerHTML = currentValue;
};
</script>
</cfoutput>
<cfparam name="url.start" default="1" >
<cfquery name="query" datasource="">
</cfquery>
<table>
<cfset totalPages = ceiling(query.recordCount)>
<cfset thisPage = ceiling(url.start)>
<cfloop query="query" startRow="1" endRow="20">
<cfoutput>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</cfoutput>
</cfloop>
</table>
<html>
<head>
</head>
<body>
<div id="text">Results = <span id="number">0</span><div>
Plus 20 Results
Minus 20 Results
</body>
</html>
I removed the database information out of the code.
Given your example code, I don't see why you would need or want to use Javascript in the first place but for the sake of answering the question,
the answer is that you cannot directly pass the value of a client-side Javascript variable to a server-side language like ColdFusion. Javascript runs client-side, such as in your browser. ColdFusion runs on a server. Because Javascript runs separately from ColdFusion you must use some means of sending the value(s) from the client side (i.e., a computer with a browser) to the server.
Possible Options:
Send a value as a URL parameter:
Plus 20 Results
or
<a href="javascript:location.href='https://www.example.com/index.cfm?start='+add(20)"/>Plus 20 Results</a>
Send a value as a POST or GET parameter via an HTML FORM:
<form action="/index.cfm" method="post">
<input type="text" name="start" value="20"/>
<input type="submit"/>
</form>
Or send a Javascript value using POST or GET with AJAX to a ColdFusion service.

Javascript - how to get a float value from an HTML input?

I am experiencing some problem retrieving float numbers value with JavaScript from HTML by clicking on a button and then process them into a PHP file.
The HTML part is inside a table (maybe is usefull for extra info):
<table style="width:100%">
<tr>
<!-- some other <td> here -->
<td>
<img name="clickImage" style="position: relative; margin: auto;" src="myImage.png" onClick="fooFloat()">
</td>
<td>
<input id="toAngleH" maxlength="6" size="6" type="text" value="" style="background-color: #ffff;"/>
<br>
<input id="toAngleV" maxlength="6" size="6" type="text"value="" style="background-color: #ffff;"/>
</td>
</tr>
</table>
And my Javascript function fooFloat() is the following:
function fooFloat()
{
//doesn't work
var $angleH = parseFloat(document.getElementById("toAngleH").value);
var $angleV = parseFloat(document.getElementById("toAngleV").value);
//doesn't work
//var $angleH = $("#toAngleH").val();
//var $angleV = $("#toAngleV").val();
$("#content").load("file.php",{ toAngleH: angleH, toAngleV: angleV });
}
In the PHP file the values are retrieved as always with the
isset($_POST["string"])
function which works fine for integer numbers, but seems I cannot process the float values into the Javascript function.
I don't know where I am wrong.
Thank you in advance for your help.
EDIT:
I finally solved the problem. I was missing an apostrophe in the PHP file...
Bye.
In http post request the data is serialized/encoded to string and posted to server. Now it's server responsibility to parse these data correctly.
As far as Javascript is concerned you are retrieving it correctly . However i think you have a typo where you storing the value in $angleH but using angleH ($ omitted).
You may wish to check network headers through debugger network tab to see what data is posted to the server.
var val = document.getElementById("toAngleV").value//string value
Did you try passing the number as a string and parsing it on the server side? I'd imagine there is some kind of issue with the point or comma. You could maybe try replacing those characters before posting and then replacing then back on the server before type changing.

Update textfield based on combobox selection using JQuery - accessing list problem

I have a Spring MVC application, use JSP+JQuery for view, and what I need is to, based on combo box selection (which gets me an index of element in list) to populate text field.
listProduct - list of products that is in the model
<form:form method="POST" commandName="productForm" name="insertRacun">
<table>
<tr>
<td class="ui-widget">Product:</td>
<td><form:select path="productListId" id="productCombobox">
<form:options items="${listProduct}"itemLabel="name" itemValue="productId"/>
</form:select>
</td>
<td class="ui-widget">Product price:</td>
<td><form:input path="priceList"
class="ui-widget ui-widget-content" id="priceInput" />
</td>
<script type="text/javascript">
var comboIndex = $("#productCombobox").val();
$("#priceInput").val(${listProduct[comboIndex].price})
});
</script>
My question is: When i put number in listProduct[] i.e. listProduct[0] it works just fine and price field gets populated, but when i want put "comboIndex" in brackets, it does nothing.
If there is another solution (not using JQuery), please post it
You are mixing client and server side code. You cannot pass a JS variable to your server code, as your server code is parsed before the page has been served up to the client.
You will need to pass the price corresponding to a particular product ID to the client by other means.
The relevant code (probably in a change event handler) should reference productCombobox selectedIndex instead:
var comboIndex = $("#productCombobox").attr("selectedIndex"); //
$("#priceInput").val(${listProduct[comboIndex].price});

jsp update request happens to be invoked by a link

<tr class="bg-row1">
<td class="td-highlighted-2">
<div align="left"><%=searchList1.getProjid()%></div>
</td>
<td class="td-highlighted-2">
<div align="left"><%=searchList1.getProjname()%></div>
</td>
</tr>
here jsp update request happens to be invoked by a link
in updateproject.jsp how can i refer projid and projname value in a text box
For this type of scenario POST is better suited,
Even if you want to stuck with GET , you can use javascript and use window.open() function for your purpose , and build URL dynamically reading fields

How to pass form values to a populate query parameters without refreshing in ColdFusion

I’m looking for a nudge in the right direction!
I have a ColdFusion page with a form which dynamically fills 3 dropdown selections using javascript (calling a function in a .js page, which in turns uses Ajax to call another .cfm page which points to a stored procedure .. and then eventually returns the results back to my original page, and fills the next select box – This keeps the page from having to refresh in between selections, PHEW!).
There are also 2 textboxes which the user is required to fill after making the 3 previous dropdown selections. Based on this user input I need to :
1) Call a query which searches a DB based on the TEXT AND SELECTION input without refreshing the page (need to preserve data)
2) Output the results to a table for the user to select a match without refreshing (preferable)
3) Submit the form and pass that value from the table to the next page which processes the request
I have a solution in place which uses all CF code to handle this page, but the page must refresh after each drop down selection in order to populate the next dropdown with a value. This works but is rather messy and doesn’t look very neat.
Do you have any advice on how I can accomplish this using the Javascript method mentioned above? I’m working with legacy code so my options are limited in reworking the entire structure, and I’d like to keep as much existing functionality as possible.
Example of drop down list structure and ajax on calling page:
In Main CFM Page:
<tr>
<td>Region :</td>
<td>
<select id="subregions" onchange="fillupRegion()">
<option></option>
<cfoutput>#regionstr#</cfoutput>
</select>
</td>
</tr>
<tr>
<td>Sub Turf :</td>
<td>
<select id="region" name="region" onchange="fillupCLLI('','region','clli',true)"></select></td>
</tr>
<tr>
<td>Street Address :</td>
<td>
<input type="text" maxlength="50" size="40" name="txtStreet" id="txtStreet"/>
</td>
</tr>
In .JS Page
function fillupRegion(){
// fill up the sub region drop down according to the selected region
$.ajax({
type: "POST",
dataType: "text",
url: "lookup_subregions.cfm",
data: "region="+ $("#subregions").val(),
timeout : 30000,
success: function(response){
if (response=="<option value=''></option>"){
$("#region").attr("disabled",true);
}else{
$("#region").attr("disabled",false);
}
$("#state option[value='']").attr("selected","selected");
$("#region").html(response);
},
error: function(){
alert("An error has occurred.");
}
});
}
Main Query which must be populated based on selections (ignore the #arguments# tags)
<cfset p=#ARGUMENTS.streetAdd#.split(" ")>
<cfquery name="getPossibleMatchQry"datasource="#request.application.dba#"
username="#request.application.dbaid#"
password="#request.application.dbapwd#">
SELECT top 25 CLLI_CODE, CLLI_CODE_COMBINED_ADDRESS as STREETADDRESS, CITY_PLACE_NAME as CITY, STATE
FROM CSMI_REF_CLLI_LAT_LONG
WHERE (UPPER(CLLI_CODE_COMBINED_ADDRESS) LIKE UPPER('#p[1]#' + '%')
<cfif gStreet EQ True>
AND UPPER(CLLI_CODE_COMBINED_ADDRESS) LIKE UPPER('% ' + '#p[2]#' +'%'))
<cfelse> )
</cfif>
AND (UPPER(CITY_PLACE_NAME) LIKE UPPER('#ARGUMENTS.city#' + '%') OR UPPER(CITY_PLACE_NAME) LIKE UPPER('%' + '#ARGUMENTS.city#' +'%'))
AND STATE = '#ARGUMENTS.state#'
ORDER BY CLLI_CODE_COMBINED_ADDRESS ASC
</cfquery>
EDIT AFTER SOLUTION:
I've decided to go the CFC approach by creating a new function in my .JS page. The function is called when a user completes the Street and City input fields. What I'm yet to figure out is how to format my function, and how to have that function/query (from the cfc) return a table (or cfgrid?) populated with the results. Here is what I have in my Function so far (the query thus far remains the same as above):
<input type="text" maxlength="50" size="40" name="txtStreet" id="txtStreet" onchange="fillupMatch()"/>
function fillupMatch(){
$.ajax({
type: "POST",
dataType: "text",
url: "lookup_CLDS_match.cfm",
data: "streetAdd="+$("#txtStreet").val(),
"city="+$("#city").val(),
"region="+$("#region").val()
timeout : 30000,
success: function(response){
$("#matches").html(response);
},
error: function(){
alert("An error has occurred");
}
});
}
Ok looks like you are using jQuery which makes this pretty easy. There are 2 ways you can approach this, you can generate them on a cfm page then load them into your existing page using something like jQuery's .load() function:
$('#selectDiv').load('components.cfm #selectdiv');
Alternatively a more native approach you can move your query generating functions into a CFC and then call it from javascript using <cfajaxproxy>. The below examples are from when this was implemented in CF8, but the syntax should be valid for CF9. Once you've made the proxy of your cfc you can use it like you would any other javascript object to call its member functions. There is an example of populating a select at the bottom of the livedocs page as well.
Documentation:
http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_a-b_3.html
Example:
<script type="text/javascript">
//Callback Function to display data.
function createTable(json){
$(json).find('result').each(function(){
var data1 = $(this).child('data1').val();
var data2 = $(this).child('data2').val();
var html = '<tr><td>'+data1+'</td><td>'+data2+'</td></tr>';
$('#tbodyID').append(html);
});
}
</script>
<table>
<thead>
</thead>
<tbody id='tbodyID'>
</tbody>
</table>

Categories

Resources