Passing Javascript combobox select value into a java method - javascript

I want to pass a selected value of a combobox into a java Method. All the posts I see refer about using HttpServletRequest and getParameter function to pass the value, but my problem is, I need the value as a string passed into a Java Method, that already exists. Any pointers how to do it?
I have seen some references of doPost method, but that really doesn't help me, as all I need is the value passed into a customized java method and use it. Any help would be deeply appreciated. I'm stuck on this for several hours.
Any clarification or extra information required, please let me know.
<SCRIPT>
function sendParam(){
var item= document.Form.item[document.Form.item.selectedIndex].value
//I need to send this value to the server side java code and process further
}
</SCRIPT>

I did it through action class.
<SCRIPT>
function sendParam(){
var item= document.Form.item[document.Form.item.selectedIndex].value
//I need to send this value to the server side java code and process further
var url = "/urlToActionClass"
document.Form.acton = url;
document.Form.submit();
}
</SCRIPT>
now the value is passed into java which I read in the action class and used it in the required Java function.

Related

JS variable is displayed as undefined when using HTML

I am working on a project on Google Apps Script. I have a JS function that returns a date (as a text). I also have an HTML document to display a form with several inputs. I would like to prefill one input with the date returned by the JS funtion. It almost works, except it displays "undefined" instead of the date, even though I know the js funtion is working fine.
Here are some code to better understand :
The input where I call the script (don't mind the onmousemove, i just didn"t find anotherway to call the script).
<input type="text" id="deliveryDate" name="deliveryDate" onmousemove="displayActiveDate()">
So it calls the folowing script.
<script>
function displayActiveDate(){
var activeDate = google.script.run.getActiveDate();
document.getElementById("deliveryDate").value = activeDate;
}
</script>
Which in turn calls getActiveDate() which is the separate JS function that returns the date.
If you have any idea on how to solve this, I will be very thankful.
google.script.run.serverSideFunction() returns undefined. In order to get the actual response value from your serverSideFunction() you need to use the withSuccessHandler() method with a callback like so:
google.script.run.withSuccessHandler(onSuccess).serverSideFunction();
function onSuccess(data) {
// do something with the data returned by the serverSideFunction()
}
Also note that you also have withFailureHandler(err) to handle any errors you server-side functions may return.
Here is the full reference
Instead of writing document.getElementById("deliveryDate").value = activeDate; type document.getElementById("deliveryDate").innerHTML= activeDate; in your script

my jQuery parameter is not recognized by the C# method in which is accessed in script area

I tried to access the my C# method in my JavaScript, but this method is not accepting the local parameters and saying, the parameter does not exist in the current context.
var typeofServiceNumber = $("#serviceType").val();
#MyStaticClass.StringEncoding(Convert.ToString(typeofServiceNumber));
The above typeofServiceNumber is not recognized by the method
Razor code is executed server side before the HTML is returned in the response stream.
Javascript is executed client side within the resultant HTML.
Therefore you cannot pass a Javascript variable through to a Razor method, and you receive the message that typeOfServiceNumber is not recognized.
To be recognized, it would either need to be handled server side via data being passed to the View (ViewBag, Model etc), or it would need to be declared and assigned to within Razor tags on the page itself.
EDIT: to clarify the last point:
var typeofServiceNumber = $("#serviceType").val();
#MyStaticClass.StringEncoding(Convert.ToString(typeofServiceNumber))
The first line you have here is all happening in the browser of the end user.
The second line is all happening on the server. You see the error message because you are trying to pass "typeofServiceNumber" to your method, and the variable isn't even declared at that point.
Without knowing exactly what you're trying to achieve it's hard for me to give a precise answer as to how to solve your problem. But here are two possibilities:
1) You know what $("#serviceType").val() is going to be before you serve the web page to the end user because that value is being set server side.
Controller:
public ActionResult MysteryController()
{
...your code here to work out what the service type is...
ViewBag.serviceType = serviceType;
return View();
}
View:
...lots of lovely html and such...
<script>
#MyStaticClass.StringEncoding(Convert.ToString(ViewBag["serviceType"]));
</script>
I can't see what the output of #MyStaticClass.StringEncoding() is but I have to assume at this point that it is doing whatever it is supposed to do.
Although the logic is split between the controller and the view, all of this is happening server side.
The second half of my point "or it would need to be declared and assigned to within Razor tags on the page itself." refers to the fact that one variation of this method could involve manipulating data in the View itself by enclosing it in a Razor code block like this:
#{
var typeofServiceNumber = #MyStaticClass.StringEncoding(Convert.ToString(ViewBag["serviceType"]));
}
The alternative, which I did not really address originally is:
2) You don't know what the value of $("#serviceType").val() is going to be before the page is loaded because it is being set by the end user and your function needs to be used before the data is submitted to the server:
If that's the case then #MyStaticClass.StringEncoding(Convert.ToString(typeofServiceNumber)) is no good to you, you will have to replicate the function in JavaScript and include it in the webpage itself.

Calling controller function from gsp

I need to call a controller function from javascript on my gsp.
I have read different solutions from hundreds of places but none worked.
The problem which I found closest to mine was this.
But I am not repeating the same mistake as this and thus the solution didn't help.
I have a tag like this which calls the javascript function
<g:select name="poNumber" noSelection="['':'Select PO Number']" from="${com.rerq.PurchaseOrder.list()}"
onchange="getProject(this.value)" />
And the javascript function looks like this
function getProject(poNumber){
var projectName = document.getElementById("projectName");
var newData = ${remoteFunction(controller: 'sow', action: 'getProject', params: ['poNumber':poNumber])};
}
And the function I need to call is
def getProject(String poNumber) {
String projectName = Sow.find("from Sow as s where s.poNumber=?", [poNumber])
return projectName
}
The controller function might have mistakes as I am completely new to groovy and grails. But my understanding is that the control isn't reaching here so this should not be the cause of any problem.
I am getting below exception
No signature of method: remoteFunction() is applicable for argument types: (java.util.LinkedHashMap) values: [[controller:sow, action:getProject, params:[poNumber:null]]]
I tried using remoteFunction() in g:select itself but it threw another exception which said
Attribute value quotes not closed ...
even though they were.
Any help is greatly appreciated.
To use remoteFunction with Grails 3 you need to add the ajax-tags plugin: org.grails.plugins:ajax-tags:1.0.0
Actually you can have your gsp recognize some Grails functions inside your js if the script is inside the gsp and anything you need for your js is created on the server side. In your case it seems you want to do an ajax call so you could have the following.
project.gsp (Consider that you already loaded jQuery)
<g:select name="poNumber" noSelection="['':'Select PO Number']" from="${com.impetus.rerq.PurchaseOrder.list()}"
onchange="getProject(this.value)" />
And in the same file you have
<script type="text/javascript">
function getProject(poNumber){
jQuery("#yourTarget").load("${createLink(action: 'getProject')}",{poNumber: poNUmber},function(response, status, xhr ){
if ( status == "error" ) {
alert("No data loaded.")
}
});
}
</script>
As you see a gstring in load("${}",... is used because it will be parsed in the server and at client side your actual js it will parse to load("yourcontrollerName/getProject",..... Why not code the url directly in the js? Because by using createLink() it is less likely to make reference mistakes.
EDIT
If you want to do this but using an external js file, you would need a way to pass the url, to the js, and use a simple load function. So something like this will be helpful
<g:select name="poNumber" noSelection="['':'Select PO Number']" from="${com.impetus.rerq.PurchaseOrder.list()}"
onchange="getProject(this.value, \'${createLink(action:'getProject')}\')" />
Once on the server onchange="getProject(this.value,\'${createLink(action:'getProject')}\')"would be parsed to onchange="getProject(this.value,'yourController/getProject')". Be wary that I might have messed up the ""s and ''s so verify your html output.
And you would need a js function that accepts the uri
function getProject(value, targetUri){
....
}
What you need to review is when is your function needed, on the server o in the client;if the functions are inside a gsp or not; And if not available, how could you pass data to them.
You cannot access grails's controller from javascript. I haven't tested it but this might work.
<g:createLink controller="sow" action="getProject", params="['poNumber':poNumber]"/>
Also, if you use Google Chrome's developer's tool, you will see how your javascript code is displayed. Make sure it is in right syntax.

Setting value of a parameter in html by calling javascript function

Is there a way to do this?
<'param name = "ticket" value = "getTicket()">
getTicket() is my Javascript function. Whatever the function returns, that should be the value of the parameter tag.
I cant set it explicitly using Javascript "document.getElem...." because I want the value to be loaded at the time of page load. Or, while the parameter is being set.
For further info, I am trying to do this for Tableau Trusted Authentication.
Are you using server-side scripting?
Isn't more effectively to do what you do using the request/response ways?
Like directly using <%=ticketValue%> (ASP way) or ${ticketValue} (JSP way)?
You may use Document.Write as follows:
<'param name = "ticket" value = "<script>
document.write(getTicket());
</script>">
You can access node from JavaScript right after it was created.
You're not obligated to wait for DOMContentLoaded event. So this code will work as expected:
<script>
function getTicket() {
return 'whatever';
}
</script>
<param name="ticket" value="" class="js-ticket">
<script>
var ticket = document.querySelector('.js-ticket');
ticket.value = getTicket();
console.log(ticket);
</script>
See demo.
This approach is better than using document.write, see good explanation.
You can use jquery $(document).ready() function callback. If jquery isn't available, then you can use the equivalence of it.
$(document).ready equivalent without jQuery
Then you can access document.getElement.

Update EditorFor according to a Dropdown: Is there any way to use a JavaScript variable inside a HTML helper on MVC4?

I have this dropdown list for a Model's property (Currency) in my View to which I have associated a JavaScript onchange function.
The goal of such function is to update some other field's (Rate) value according to a Dictionary property from the model (which maps Currencies to their Rate).
<td>
#Html.DropDownListFor(model => model.Currency, new SelectList(ViewBag.CurrencyList, "Code", "Code"), new {onchange="update(this)"})
#Html.ValidationMessageFor(model => model.Currency)
<script type="text/javascript">
function update(elem) {
// alert("Currency changed!")
document.getElementById("#Html.IdFor(model => model.Rate)").value = '#Model.Currencies[<I_WISH_I_COULD_PUT_A_JS_VARIABLE_IN_HERE>]'
}
</script>
</td>
I want that "I_WISH_I_COULD_PUT_A_JS_VARIABLE_IN_HERE" to be elem.value, but I get a syntax error as the JS variable is interpreted as a literal.
I can't seem to call an HTML helper with a Javascript value in it.
My goal is to update an EditorFor field according to the value selected in the combo box. but probably there's something wrong with my approach?
Any help would be appreciated.
You're thinking about this the wrong way. HTML, CSS and JavaScript are output of your ASP.NET MVC web application project. JavaScript can't influence your web application the way you're trying above. There's no live connection between your MVC web application and JavaScript that somehow magically respond to one another.
To get this to work, I would place the values within #Modal.Currencies in some sort of JavaScript array. Then use that array to locate the value you need (with the JavaScript variable) to update the element with.
As I said in my comment, my approach didn't make sense at all as I was mixing server-side code with client-side.
I used ajax inside my function update(elem) to retrieve the correct value and update the correspondent field:
$.ajax({
type: "GET",
url: "Currency?code=" + elem.value,
success: function (msg) {
document.getElementById(RateId).value = msg;
}
});
I hope this might help someone in the future. Cheers.

Categories