Call Javascript function in Servlet, after servlet responce - javascript

I have a jsp page. There is a form in the jsp page and when I press submit the control goes to the servlet and the servlet sends the response in the same jsp. I want to call a javascript fuction after the response is called.
String operation = request.getParameter("operation");
if (operation.equals("create")) {
String value = null;
Map<String, String> requestMap = new HashMap<>();
String entity = request.getParameter("entity");
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
if (paramName.equals("operation") || paramName.equals("entity")) {
value = request.getParameter(paramName);
} else {
value = Constraints.toTitleCase(request.getParameter(paramName));
}
requestMap.forEach((k,v)->System.out.println("{KeY} :"+k+".....{VAlue} :"+v));
requestMap.put(paramName, value);
}
masterHelper.processRequest(requestMap);
log.debug("js");
response.getOutputStream().println("<script>sucess();('hello');</script>");
response.sendRedirect("user/master/" + entity + ".jsp");
}

Looks like you are redirecting the page .
response.sendRedirect("user/master/" + entity + ".jsp");
try sending the function definition also.

All you can do is use just set extra variable for it and then based on the value of that variable call the javascript function. You can follow steps below
In your servlet set a boolean variable
boolean isResponse=true;
Then add it to your response
request.setAttribute("isResponse", isResponse);
the add below code in your jsp.
${ isResponse=="true"?'windows.onLoad=functionname()':'' }
And you are done with it.

Related

How to get global variable and global function inside JavaScript

At the time of login to my app, I stored the login details and token details inside the session of a class. Now on my aspx page, I have to write a javascript function, which should check if the token got expired within 5 mins or minutes. If then I have to call an API to update the access token with a refresh token. This API I have written in a global class. How can I call this method inside JavaScript? and also how can I get the values stored in the session of the class (ex: login_token_expires_in) inside javascript?
`public class GlobalVariables
{
public int login_user_role = 0;
public string login_user_name = string.Empty;
public string login_user_id = string.Empty;
public string login_token = string.Empty;
public string login_refresh_token = string.Empty;
public int login_token_expires_in = 0;//1799 sec; 29.9833 minute//1799000
}
public class GlobalFunctions
{
private bool GetLoginTokenWithRefreshToken(string username, string refresh_token)
{
GlobalVariables obj_GlobalVariables = (GlobalVariables)HttpContext.Current.Session["objGlobalVariableClass"];
bool status = false;
string log_data = string.Empty;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(GlobalVariables.WebAPITokenURI);
HttpResponseMessage response =
client.PostAsync("e_token",
new StringContent(string.Format("grant_type=refresh_token&username={0}&refresh_token={1}",
HttpUtility.UrlEncode(username),
HttpUtility.UrlEncode(refresh_token)), Encoding.UTF8,
"application/x-www-form-urlencoded")).Result;
if (response.IsSuccessStatusCode)
{
string resultJSON = response.Content.ReadAsStringAsync().Result;
e_Token result = JsonConvert.DeserializeObject<e_Token>(resultJSON);
obj_GlobalVariables.login_token = result.access_token;
obj_GlobalVariables.login_refresh_token = result.refresh_token;
obj_GlobalVariables.login_token_expires_in = Convert.ToInt32(result.expires_in * 1000);//seconds to millisec
status = true;
}
else
{
status = false;
}
return status;
}
}`
When login success, stores the login details in GlobalVariables class
`GlobalVariables obj_GlobalVariables = new GlobalVariables();
obj_GlobalVariables.login_token = result.access_token;
obj_GlobalVariables.login_token_expires_in = Convert.ToInt32(result.expires_in*1000);//seconds to millisec
obj_GlobalVariables.login_refresh_token=result.refresh_token;
obj_GlobalVariables.login_user_name =result.login_user_name;
etc..`
Javascript on Page1.aspx
`<script type="text/javascript">
var idleSecondsTimer = null;
idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
//have to check if time after login >= login_token_expires_in - 5 seconds
//then need to call the function GetLoginTokenWithRefreshToken(username, refresh_token)
}
</script>`
I want to know how to get the c# global variables and functions inside javascript
stored the login details and token details inside the session of a class.
No, no, no!
You mean you create a class instance, and then SHOVE it into session() to be saved, right? I don't see any "session" in a class here - so this MUST be cleared up by you. You don't have global variables here. And you can't use a static class, since it will be shared/used/the same for all users.
And a global scoped variable will go out of scope. So, you mean you create a class instance, set the values, and THEN save into session(), of which THEN you can retrieve for use on subsequent post-backs.
As for using/having/enjoying those values client side?
Well, you have quite a few options.
You can create a web method that returns the values (so, that would be a client side ajax call).
Another way?
In some cases, I will not make a web method call, and simple shove that server side class into a simple (one) hidden field on the page. (you just shove in the class as serialized), and then client side can grab that simple string, de serialize it into a client side object, and once again, then js client side code on that given page has use of all the values of that class.
It really depends on how many pages, and where you need such values from js code, but I would think in most cases, a web method would be the way to go.
However, lets use the "simple" hidden field, and SEND the class to the client side.
So, say this simple code server side:
For this example, I just shoved all the code right into the existing web page (so you can even cut + paste and try this).
So, say this code:
public class cHotel
{
public string FirstName = "";
public string LastName = "";
public string HotelName = "";
public string Description = "";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadMyData();
}
}
void LoadMyData()
{
DataRow drHotel =
General.MyRst("SELECT * FROM tblHotelsA WHERE ID = 16").Rows[0];
cHotel MyHotel = new cHotel();
MyHotel.FirstName = drHotel["FirstName"].ToString();
MyHotel.LastName = drHotel["LastName"].ToString();
MyHotel.HotelName= drHotel["HotelName"].ToString();
MyHotel.Description = drHotel["Description"].ToString();
JavaScriptSerializer jsS = new JavaScriptSerializer();
this.HotelInfo.Value = jsS.Serialize(MyHotel);
}
And the client side markup is this (I do have jQuery, but that one selector could be replaced with getelementByID - the rest is only js code - not jQuery.
<asp:HiddenField ID="HotelInfo" runat="server" ClientIDMode="Static" />
<div style="padding:40px">
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="test1();return false;"
/>
</div>
<script>
function test1() {
var MyHotel = JSON.parse($('#HotelInfo').val())
alert("Hotel name = " + MyHotel.HotelName)
alert("Description = " + MyHotel.Description)
}
</script>
So, when I run this page, and click on the button, I get/see this:
So, the above is a great way to send the class to the page, its simple, and no fancy web methods or anything is required.
And kind of nice, since that hidden field is available to ANY and all routines in the client side js code. So, clean, little code, easy. And the hidden field will survive post-backs and round trips. So, simple, easy, clean, and very little code. and hiddenfield does have viewstate.
However, these days, a LOT of people would suggest that you use a web method, and thus that web method could called from any js code. But, you are now dealing with a asynchronous call, and more moving parts.
However, lets below the above posted c# code, lets add a mebmethod, and give that a shot, shall we?
So, after above code, we now have this:
[WebMethod()]
public static cHotel GetHotel()
{
DataRow drHotel =
General.MyRst("SELECT * FROM tblHotelsA WHERE ID = 16").Rows[0];
cHotel MyHotel = new cHotel();
MyHotel.FirstName = drHotel["FirstName"].ToString();
MyHotel.LastName = drHotel["LastName"].ToString();
MyHotel.HotelName = drHotel["HotelName"].ToString();
MyHotel.Description = drHotel["Description"].ToString();
return MyHotel;
}
Ok, so now in client side, we will call the above web method (ajax call).
So, this:
function test2() {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetHotel",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { },
success: function (response) {
var MyHotel = response.d;
alert("Hotel name = " + MyHotel.HotelName)
alert("Description = " + MyHotel.Description)
},
failure: function (response) {
alert(response.d);
}
});
}
Again, the result would be the same. so, either the "hidden field" trick, or a standard webmethod (that's a end point) call will work.
And I suppose you could make some "single" webmethods that reutrn ONLY one value out of the class. Do keep in mind that while the web methods are "static" (it does not have use of controls on the web page, it can have use of session()).
So, say this:
[WebMethod(EnableSession = true)]
public static cHotel GetHotel()
{
DataRow drHotel =
bla bla bla

Controller doesn't receive one parameter from url query

ASP.NET, I have a controller with this GET method:
public ActionResult Index(String state, String searchNumber, String searchCustomer, int? page)
{
}
in the view I call it in this way:
$("#btnSearch").click(function (event) {
var params = {
state: '#ViewBag.State',
searchNumber: $('input[name=searchNumber]').val(),
searchCustomer: $('input[name=searchCustomer]').val()
};
var url = window.location.href + "/Index/?" + jQuery.param(params);
window.location.href = url;
});
where the #ViewBag.State is a String received from the controller while the other fields are from texboxes.
Here a real example of the url value:
"http://localhost:49396/Orders/Index/?state=Opened&searchNumber=17&searchCustomer="
In the controller Index function the searchNumber variable is set to "17" but state to null.
Why the first one is not recognized?
#ViewBag.State is Razor syntax. Razor is working in your cshtml files, but javascript files are not parsed/processed.
One way to get the property anyway is to add an hidden field to your view with the value set to #ViewBag.State. Then read the value from the hidden field in javascript - just like you are already doing it for the other two properties.

URL parameters on javascript

I´m making a call using javascript and I would like to send an array:
var selected = [];
selected=getAllEnginesIdsSelected();
console.log("selected: "+selected);
$.getJSON('/call/' + selected,
function(myList) {
The funcion that I use in Javascript to retrieve array is:
function getAllEnginesIdsSelected() {
var selected = [];
$("input:checkbox[id^='engine_']:checked").each(function(){
var ele=$(this)[0].id;
selected.push(ele);
});
return selected;
}
Console.log retrieves selected: 2,5
In MVC Controller I have
#RequestMapping(method = RequestMethod.GET, value = "/call/{selected}")
public List<List<myList>> myCall(#RequestParam(value="selected[]") String[] selected){
I gives an error. I don´t want to use AJAX. This is posible to send?
selected is an array, which you are joining to a string in the URL. Try something like $.getJSON('/call/?selected=[' + selected.join(',')]

Passing json object from Android/iOS native to javascript

Is there any way to pass JSONObject from android to javascript. We are using WebView.evaluateJavascript mehtod and are able to send only String type object. In JS if we are checking the method paramter;s typeof(data) then it is displaying as string but in iOS it displays typeof(data) as OBJECT.
In both android and iOS we are passing String and NSString.
JS method is:
response: function(id, err, data) {
var dataObj;
if(typeof(data) == 'string' ){
dataObj = JSON.parse(data || '{}');
}
}
Android call:
String responseStr = "{\"ok\":\"ok\"}";
String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')";
webView.evaluateJavascript(nativeToWebMethod, null);
Just send it as if you were loading a url:
private void loadJS(String jsonResponse){
mWebView.loadUrl("javascript:" + "(function(){" + "yourJsMethodName" + "(" +jsonResponse + ");" + "})()");
}
This will execute a JS Code that will call a function called yourJsMethodName and will pass the JSON as parameter.
Consider execute the last code in the Main Thread
I find out the issue, it was in the way I was sending data:
String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')";
should be replaced with
String nativeToWebMethod = "javascript:window.nativeService.response("1",'',"+responseStr+")";
removed single quote around the responseStr.

how to return error message from in controller rather than returning modelAndView in spring mvc

I am passing an id in controller from a list page, where it is getting processed and result is set in model.addObject().
Also, I am setting view in new ModelAndView("viewName"). So the new data is shown on the new jsp. Now I am adding a logic that if the id passed from list page is same as userId in session, I need to show error message "You cannot do this as the user selected is yourslef" on same list page rather than showing new page with new data.
This is my method syntax.
public ModelAndView showdetails(#RequestParam ("userLogin") UserLogin userLogin){....
return modelAndView;
}
Please suggest a way to do it.
As this method returns the view , you could map a object to it something like this ,
public ModelAndView showdetails(#RequestParam ("userLogin") UserLogin userLogin){....
// Verify your session here
if (session.getAttribute("name").equals("name")
{
string vale = "You cannot do this as the user selected is yourslef"
return modelAndView("viewname","value",value);
}
And in your jsp ,
use EL to print it ,
${value}
Hope it helps !!
It's done through JS. And your controller method should return
ResponseEntity<Map<String,String>>. When you select a user from a list page, in the function of onchange() event you send request by Ajax (XMLHttpRequest) and you will get responseText and parse it on JSON. Then you will get the message and alter some content of your document to show it.
public ResponseEntity<Map<String,String>> showdetails(#RequestParam("userLogin") UserLogin userLogin){
Map<String,String> resp = new HashMap<>();
if (session.getAttribute("name").equals("name")){
resp.put("message","You cannot do this as the user selected is yourslef");
}
return ResponseEntity.status(HttpStatus.OK).body(resp);
}
Then your JS should be:
function checkUser(userId){
const Http = new XMLHttpRequest();
const url="https://your.domain.com/...";
Http.onreadystatechange = (e) => {
if (Http.readyState===Http.DONE && Http.responseText!=""){
var json = JSON.parse(Http.responseText);
document.getElementById("msgElement").value=json['message'];
}
}
Http.onerror = () => alert("Request failed");
Http.open("GET", url);
Http.send();
}

Categories

Resources