I have a function in js file(exp : validateMyfile.js) that get a string parameter, this String has a value in myFile.properties and I need this value.
Now I want to get parameter value by spring message source.
How to use spring message source inside js file?
function validate(msg){
-- so I need msg value (value iside myFile.properties);
}
We normally read the message into a javascript variable in jsp file before passing it to a js function as follows
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<script type="text/javascript">
var successmsg = "<fmt:message key='message.key'/>";
function validate(){
alert(successmsg);
}
</script>
Sometimes, we also pass it as a message from the Controller for a ajax call.
#Controller
public class EmployeeController{
#Value("${employee.add.success}")
private String successMessage;
#Value("${employee.add.failure}")
private String failureMessage;
#ResponseBody
#RequestMapping("/addEmployee")
public String addEmployee(...){
...
if(added){
StatusObject status = new StatusObject();
status.setCode(..);
status.setMessage(successMessage);
}else{
StatusObject status = new StatusObject();
status.setCode(..);
status.setMessage(failureMessage);
}
//return status object
}
}
And access it as follows
$.ajax({
...
success: function(status){
$("#result").text(status.message);
}
});
Related
I have this URL
var url = "/test/Create/" + $("#hdnFlag").val() +"?CmpT="+"Ilim";
window.location.href = url;
and in my Test controller I do this to get query string value
tM_PMO.Type = Request.QueryString["CmpT"];
But always give me null values.
There is a difference between the GET and POST types.
Query string can be read with the URL of the GET request. However, you cannot read the Query string value in the URL when you make a POST request. For this you need to submit it to the server.
Below I give you a few examples of usage.
GET Request
You can read Query string with URL as below
public ActionResult Test(string CmpT)
{
if (!string.IsNullOrWhiteSpace(CmpT))
{
//your codes...
}else
{ }
return View();
}
POST Request
If you are making a POST request and trying to read from the URL, it will return null. In order to read it, you need to send this value to the server as follows.
1st way : In your Html.BeginForm in your View Below, submit Query string as below and read this value as Action parameter
View Page
#using (Html.BeginForm("Test", "XController", new { returnUrl = Request.QueryString["CmpT"] }, FormMethod.Post, new { role = "form" }))
{
<button type="submit">Send</button>
}
Controller
public ActionResult Test(string returnUrl)
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//your codes...
}else
{ }
return View();
}
2nd way : Create a hidden form element as part of the form between the Html.BeginForm tags in your view page and give its value as a query string. Then call it in Action method like below.
View Page
#using (Html.BeginForm("Test", "XController", FormMethod.Post, new { role = "form" }))
{
#Html.Hidden("returnUrl", Request.QueryString["CmpT"])
<button type="submit">Send</button>
}
Controller
public ActionResult Test(string returnUrl)
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//your codes...
}else
{ }
return View();
}
or for multiple form items (You can also access other form elements this way)
public ActionResult Test(FormCollection fc)
{
string _returnUrl = fc["returnUrl"];
if (!string.IsNullOrWhiteSpace(_returnUrl))
{
//your codes...
}else
{ }
return View();
}
I hope you are looking for below code sample where we just fetch the value in url which we says query string:
Request.QueryString["querystringparamname"].ToString();
You can assign this in any Var and use accordingly.
This is my Controller:
{#RequestMapping("/component")
public String component(Model model) {
Class obj=new Class ();
JSONObject data=obj.fetchData();
model.addAttribute("message", obj.getMessage());
model.addAttribute("data", data);
return "component";
}}
I am able to print data in the view of component.html like this:
<p th:text=${data}></p>
but how do I get the data in Java Script? js_component.js is my source.
<script th:inline="javascript" src="js_component.js"></script>
I've already tried this code in js_component.js but it does not work.
/*<![CDATA[*/
var json=/*[[${data}]]*/ 'data';
var msg=/*[[${message}]]*/ 'message';
/*]]>*/
how do I get the data in Java Script?
Did you try to return "js_component.js" at your controller.
#RequestMapping("/component")
public String component(Model model) {
Class obj=new Class ();
JSONObject data=obj.fetchData();
model.addAttribute("message", obj.getMessage());
model.addAttribute("data", data);
return "js_component.js"; <==
}
Trying to use public properties from C# code behind and want to read the variable value from a JavaScript function
JavaScript function:
function IsAgentInProgram()
{
var optStatus = "<%=AgentOptInStatus%>";
if (optStatus == "True")
alert("You are opted in!");
else
alert ("You are opted OUT");
}
C# code behind
public bool AgentOptInStatus;
private void Page_Load(object sender, System.EventArgs e)
{
this.AgentOptInStatus = true;
}
This does not work. Output comes back as You are opted OUT. I also did an alert on optStatus and it comes back with: "<%=AgentOptInStatus%>"
Am I missing something?
You cannot read the client side variables directly in the codebehind. What you can do is creating a hidden field and setting the value with javascript, then you can read it in c#.
<asp:HiddenField ID="hdnfldVariable" runat="server" />
JS:
<script type="text/javascript">
var somefunction = function () {
var hdnfldVariable = document.getElementById('hdnfldVariable');
hdnfldVariable.value = 'value from javascript';
}
</script>
c# :
string selected = hdnfldVariable.Value.ToString();
Another option is to make an HTTP request to the server to call a function from a controller passing the data as parameters.
I have created a asmx web service as follows:
[ScriptService]
public class CurrencyData : System.Web.Services.WebService
{
[WebMethod]
public string DisplayCurrency(double currency, string symbol ,string format)
{
switch(format)
{
case "short": symbol = "EUR";
break;
case "long": symbol = "EURO";
break;
case "simple":
break;
}
return currency.ToString() + symbol;
}
}
On the client side I have created an external js script to call above service containing the following code:
$(document).ready(function displaycurrency(monval, sym, fmt) {
var output;
$.ajax({
type: "POST",
url: "http://localhost:60413/CurrencyData.asmx/DisplayCurrency",
data: "currency=" + monval + "&symbol=" + sym + "&format=" + fmt + "", //posting the required currency & symbol
dataType: "text",
success: function (data) {
var xmlout = $.parseXML(data);
output = xmlout.childNodes[0].innerHTML; //getting the currency value from xml
}
});
return output;
});
I am using the the defined function to be called in an html page to display the currency value in between script tags:
<p id="#price" ><script>displaycurrency("22.56", "$", "long")</script></p>
<script type="text/javascript" src="~/Scripts/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="~/Scripts/CurrencyHLPR.js">/script>
//external js
But when I am trying to run the code it is giving "displaycurrency is not defined" error. I intend to used this method in multiple places in the html to print different currency formats. I am not very familiar in consuming web services through scripts/ajax, so not sure of other approach. Please give a solution.
It's a bit hard for me to fully understand the outcome you want and the process, lacking background information on the project and all. Nevertheless, here's how I made it work. My example is really basic, but I suppose you'll be able to adapt it to your need.
I my JS file, I first obtain the value of the P tag, which I changed the configuration a bit (Instead of calling the function inside the P tag). I split the string into an array to obtain each parameters. I then call a function which in turn calls the ajax function. Once the result is returned from the webservice, I display the outcome in a new P tag, to show that the call was successful.
I changed your WebService code a bit, I stripped out your CurrencyData Class. Not knowing your full intent, you'll have to tell me if this class is mandatory or not and I'll rectify the situation.
Here is the WebService.cs. Note that the 'using System.Web.Script.Services;' is mandatory if you want to use your DisplayCurrency method with an AJAX call:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
//[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[ScriptMethod]
[WebMethod]
public string DisplayCurrency(double currency, string symbol, string format)
{
switch (format)
{
case "short": symbol = "EUR";
break;
case "long": symbol = "EURO";
break;
case "simple":
break;
}
return currency.ToString() + " " + symbol;
}
}
On the client side, I added the ajax code in a JS file, main.js:
//Document ready
$(document).ready(function () {
var results;
//Get P tag text
var testStr = $('#price').text();
//Split string into an array with a character delimiter
var arrayT = testStr.split(',');
//Call displaycurrency function. Each array index represents a function parameter
displaycurrency(arrayT[0], arrayT[1], arrayT[2]);
});
//displaycurrency function
var output;
function displaycurrency(monval, sym, fmt) {
$.ajax({
type: "POST",
url: "/WebService.asmx/DisplayCurrency",
data: "currency=" + monval + "&symbol=" + sym + "&format=" + fmt + "", //posting the required currency & symbol
dataType: "text",
success: function (data) {
var xmlout = $.parseXML(data);
output = xmlout.childNodes[0].innerHTML; //getting the currency value from xml
//Display result in another P tag
$(".result").text(output);
}
});
}
The simple index.html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="/js/main.js"></script>
</head>
<body>
<p id="price">22.56,$,long</p>
<p class="result"></p>
</body>
</html>
I have a registration form where I am validating the "preferred login id" using AJAX so it searches the users table and shows if it's available or not, and it displays next to the text box "username available" or "username not available".
My requirement is when it's not available I want to pass the text "username not available" back to the javascript in the JSP from the Servlet so that I can stop the user from proceeding the form. I believe I can do it using AJAX. But I dont know how to do it. Could someone help me on this with the code?
I would use JQuery, and the get() method in particular as an example
Here is a pseudo solution (didn't test it, but it's the basic approach I would use)
JavaScript
var userIsAvailable = false;
function checkUsernameAvailability(userIdToCheck){
$.get("pathToServlet",{userId: userIdToCheck},function(resultMessage){
userIsAvailable = resultMessage=="username available" //this is bad practice, just an example, pass true/false
$("#userAvailabilityMessage").text(resultMessage);
}
});
HTML
<form onsubmit="if(!userIsAvailable){alert('user is not available')}; return userIsAvailable">
<label for="userId">preferred login id<label>
<input id="userId" ... type="text" onblur="checkUsernameAvailability(this.value)">
<div id="userAvailabilityMessage" />
...
</form>
Servlet (partial)
#WebServlet("/pathToServlet")
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String result;
if(isUserNameAvailable(request.getParameter("userId"))){
result = "username available";
}else{
result = "username not available";
}
response.setContentType("text/plain");
response.getWriter().print(result);
}
}
You need to send object with some flag in message. You can use json for this.
On servlet side:
// This object we will transfere from java to javascript
public class Message {
private boolean error;
private String errorMessage;
// Getters and setters ommited
}
// Servlet code - return content
Message message = new Message();
message.setError(true);
message.setErrorMessage("Your error message");
Gson gson = new Gson(); // GSON - java json library from Google. I prefer it
String content = gson.toJson(message);
response.setContentType("text/json");
response.getWriter().print(content);
And finally javascript code:
function processRequest() {
var result = jQuery.ajax ({
url: "your.url",
method: "post",
async: false,
data: "your=data&andsomedate=somedata"
});
// Creating object from json
var message = jQuery.parseJSON(result.responseText);
// Now we can access all object fields:
if(message.error) {
alert("Error message: " + message.errorMessage);
}
}