How to call variable from java inside the js in webview - javascript

I am filling the user name box automaticly in webview application. But ı need to fill the blanks with wariable which defined in java code here is my code. I want to use variable in my java code instade of "PASS" and "NAME"
javascript:
document.getElementById('horde_user').value='NAME';" +"javascript:document.getElementById('horde_pass').value='PASS';"
java:
final String js = "javascript:document.getElementById('horde_user').value='NAME';" +"javascript:document.getElementById('horde_pass').value='PASS';"+"javascript:documentgetElementsByName('login_button')[0].click()";
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url){
if(Build.VERSION.SDK_INT >= 19){
view.evaluateJavascript(js, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
}
});
}
}
});

I recommend you to create a javascript function like :
function login(NAME, PASS)
{
document.getElementById('horde_user').value=pass;
document.getElementById('horde_pass').value=id;
document.getElementsByName('login_button')[0].click();
}
And then from your app code
String id = "myid"; //Get val from the dialog
String pass = "mypass"; //Get val from the dialog
webview.loadUrl("javascript:login('"+NAME+"','"+PASS+"')");
if you need call java from js you can folow this post
Hope it helps ;)

Related

How to load with jquery json data from a backing bean in a custom JSF component?

In short, what is the best way in JSF 2.2 to load json data from a backing bean into a javascript prog that runs in a browser.
I'm porting a dirty hacked iframed visjs network graph to JSF 2.2 - Primefaces 6.1. We have all special tags in a jsf tag library as custom UiComponent's in a jar module. I added a new graph tag, an extended UiComponentBase class, to the tag library and put all visjs javascript files with #ResourceDependency to the class. The tag loads fine, but jquery try to open a url to load json formatted graph coordinates:
$.ajax({
url: "/ajax/getNetwork",
type: "POST",
data: "",
dataType: "json",
success: showNetwork,
error: showError
});
On the old iframe solution, visjs load all data via this url.
I read some things about a single xhtml page with an <h:outputText>, a servlet or a JAXRS rest service endpoint, but these solutions does not fit into a taglibrary and must be configurated in the web.xml of the web project. Is there a way to do it with ajax events, or an ajaxBehavior in a tag library?
Thanks in advance.
The graph UiComponent in the taglib works now as expected. A extended datamodel is filled in a backing bean, similar like the lazy datamodel of the primefaces datatable. The jQuery url request from the client side in the web browser is catched with a custom PhaseListener. There was no way to access the UiComponent from the PhaseListener, because the UiViewRoot component tree was empty. So I put the datamodel in the graph UiComponent class into the SessionMap and can access the datamodel in the PhaseListener. I'm not sure that is the best way, to do this. Here is the custom PhaseListener:
public class GraphPhaseListener implements PhaseListener {
private TopologyModel topoModel;
private PhaseId phaseId = PhaseId.RENDER_RESPONSE;
#Override
public void beforePhase(PhaseEvent event) {
FacesContext context = event.getFacesContext();
Object obj = context.getExternalContext().getRequest();
if(!(obj instanceof HttpServletRequest)) {
return;
}
HttpServletRequest request = (HttpServletRequest) obj;
if(!("true").equals(request.getHeader("networkAjax")) || !request.getMethod().equals("POST")) {
return;
}
Map<String, Object> sessionMap = event.getFacesContext().getExternalContext().getSessionMap();
Object object = sessionMap.get(EnhancedGraphRenderer.GRAPH_TOPOLOGIE_KEY);
if(object == null || !(object instanceof TopologyModel)) {
return;
}
topoModel = (TopologyModel) object;
String graphAction = request.getHeader("graphAction");
String actionResponse = "";
if(graphAction==null) {
return;
}
switch(graphAction) {
case "getNetwork":
actionResponse = topoModel.getJsonNetwork();
break;
case "getNodeTypes":
actionResponse = topoModel.getJsonNodeTypes();
//actionRespoonse = topoModel.getFromAction("{node_type:switch, node_id: 2, request: children}")
break;
default:
actionResponse = "{}";
}
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
try {
PrintWriter output = response.getWriter();
output.print(actionResponse);
context.responseComplete();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
public void afterPhase(PhaseEvent arg0) {
}
#Override
public PhaseId getPhaseId() {
return phaseId;
}
}
I hope that helps others, sugestions for improvement are welcome.

In Spring Boot ,During click event Html Page Redirect and Loading the values in Dropdown components using Jquery /Thymeleaf

I am using STS 3.9.0 Tool, my project is based on Spring Boot, Thymeleaf, MySQL, Html-Bootstrap and JQuery.
In Spring Boot, during a click event the Html page needs to redirect to another page and load the dynamically generated values in Dropdown components using Jquery or Thymeleaf.
Explanation
HTML click event to call #Controller to redirecting another Html page:
#RequestMapping(value = "/getflat", method = RequestMethod.GET)
public String propertyRegistration() {
return "FlatReg";
}
The URL will Be localhost:8080/getflat It will rediect to FlatReg.html, which is located in template folder.
and during load time, again hit #RestController URL to fetch the data from the DB and Load the data to Dropdown Controller
#PostMapping("/flatreg/saveflat")
public ResponseMsg doSaveFlatDetails() {
ResponseMsg responseMsg = new ResponseMsg();
try {
// My DB call Goes Here
} catch (Exception e) {
// TODO: handle exception
}
return responseMsg;
}
ResponseMsg class Like
public class ResponseMsg {
private String status;
private Object dataObj;
public ResponseMsg() {
}
public ResponseMsg(String status, Object dataObj) {
super();
this.status = status;
this.dataObj = dataObj;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getDataObj() {
return dataObj;
}
public void setDataObj(Object dataObj) {
this.dataObj = dataObj;
}
}
I don't know how to achieve this. Is there any other way? Thanks in advance.
You have two ways to achieve this.
Before rendering the page from the Controller method propertyRegistration(), add all the data you need to display in the page FlatReg page like so.
#RequestMapping(value = "/getflat", method = RequestMethod.GET)
public ModelAndView propertyRegistration() {
ModelAndView modelAndView = new ModelAndView("FlatReg");
modelAndView.addObject("data", service.getData()); //Get data from your service layer and set it in the ModelAndView to be later retreived in your FlatReg page.
return "FlatReg";
}
The second way would be to load the "FlatReg" page as you are doing right now and then using Ajax call your Controller method doSaveFlatDetails to get the required data. Check this link on how to make an ajax call.
Hope this helps.

How can I send complex JavaScript object to ASP.net WebMethod?

I'm trying send my client-side custom object (JavaScript) to ASP.net Web Method. I use jQuery Ajax command to perform this operation.
There a example of my object:
function Customer() {
this.Name = "";
this.Surname = "";
this.Addresses = new Array();
}
I load data with this method:
function buildCurrentCustomer() {
var currentCustomer = new Customer();
/** General Info **/
currentCustomer.Name = $("#Name").val();
currentCustomer.Surname = $("#Surname").val();
currentCustomer.Addresses = new Array();
currentCustomer.Addresses["HOME"] = $("#adHome").val();
currentCustomer.Addresses["OFFICE"] = $("#adOffice").val();
return currentCustomer;
}
And finally I send data with this code:
$.ajax({
type: "POST",
url: "../_layouts/CustomerManager/MasterPage.aspx/SetCustomer",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{customer: " + JSON.stringify(currentCustomer) + "}",
cache: false,
success: function (result) {
},
error: function (ex) {
WriteToConsole(ex.responseText);
}
});
My server-side methods is like that:
[WebMethod]
public static bool SetCustomer(CustomerModel Customer)
{
//My code...
}
and my CustomerModel class is like that:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common.Model.JavaScriptModel
{
public class CustomerModel
{
/** General Info **/
public string Name {get;set;}
public string Surname {get;set;}
public Dictionary<string, string> Addresses { get; set; }
}
}
The problem is that when I execute Ajax Call server-side method doesn't execute. If I change signature of server-side method in:
public static bool SetCustomer(List<CustomerModel> Customer)
SetCustomer method is executed but the List is empty.
Why have I this problem? Where can I find documentation about this functionality?
Thanks
first, if you use the data like this
data: "{customer: " + JSON.stringify(currentCustomer) + "}",
on the code behind, you need to take the same parameter customer and not Customer, so this
public static bool SetCustomer(CustomerModel Customer) { ... }
needs to be changed to
public static bool SetCustomer(CustomerModel customer) { ... }
second, your Customer object in the javascript is like this if translated to asp.net
string Name;
string Surname;
List<string> Addresses;
but your class in the code behind for Addresses is using
Dictionary<string, string>
thus causing your data from client side can't be parsed in the server side and return an error to the client side, so you need to change your Addresses class to
public List<string> Addresses { get; set; }
and lastly, your code inside buildCurrentCustomer for the Addresses is being set like this
currentCustomer.Addresses = new Array();
currentCustomer.Addresses["HOME"] = $("#adHome").val();
currentCustomer.Addresses["OFFICE"] = $("#adOffice").val();
this will never add a value to Addresses since it's type is an array, but you set the value to it as if it was an object, so if you want to stick to use an array, you need to change it to
currentCustomer.Addresses = new Array();
currentCustomer.Addresses.push($("#adHome").val());
currentCustomer.Addresses.push($("#adOffice").val());
*Note:
use this if you want to use the Addresses as an array, but if you need the Addresses to be an object that contains HOME and OFFICE, I'll Edit the answer
Edit:
perhaps you can use a javascript object like this
currentCustomer.Addresses = {};
currentCustomer.Addresses["Home"] = $("#adHome").val();
currentCustomer.Addresses["Office"] = $("#adOffice").val();
to make the equivalent for Dictionary<string,string> but if it didn't work you could change your Addresses to class too like this
public List<Address> Addresses { get; set; }
and add class Address
public class Address
{
public string Home {get;set;}
public string Office {get;set;}
}
I myself never used a Dictionary myself, so I don't know if it's the same
You can change your source code like this..
AJAX-
data: JSON.stringify({'customer':currentCustomer});
ASP.net Web Method-
[WebMethod]
public static bool SetCustomer(object customer)
{
CustomerModel CM = new CustomerModel();
_Serializer = new JavaScriptSerializer();
_StringBuilder = new StringBuilder();
_Serializer.Serialize(customer, _StringBuilder);
CM = _Serializer.Deserialize<CustomerModel>(_StringBuilder.ToString());
}
Note that you have to initialize _Serializer and the _StringBuilder properties at the top of the page as global variables...
public static JavaScriptSerializer _Serializer;
public static StringBuilder _StringBuilder;

Pass List<int> from Javascript to AJAX-Enabled WCF in ASP.Net page

I am calling a WCF method from an ASP.Net page, but I am getting format exception when WCF tries to deserialize the recordIds parameter received from JavaScript.
The first parameter passed to the WCF method needs to be of List type. Is there something wrong I have done in using JSON.stringify?
Javascript Code to call WCF
function Update() {
var myarray1 = new Array();
myarray1[0] = 1;
myarray1[1] = 11;
myarray1[2] = 14;
WCFService1.AJAXEnabledService.BatchUpdateRecords(
JSON.stringify({recordIDs: myarray1}) , "ddsd", "gggg",
updateGrid, OnError);
}
WCF method being called by above JavaScript
[OperationContract]
public bool BatchUpdateRecords(List<int> recordIds, string columnNameToUpdate, string columnValue)
{
DataTable tierIDsTable = new DataTable("RecordIds");
tierIDsTable.Columns.Add(new DataColumn("Integer", typeof(Int32)));
tierIDsTable.PrimaryKey = new DataColumn[] { tierIDsTable.Columns["TierId"] };
foreach (int recordId in recordIds)
{
tierIDsTable.Rows.Add(recordId);
}
return true;
}
Not 100% sure, but have you tried this?
WCFService1.AJAXEnabledService.BatchUpdateRecords(
myarray1,
"ddsd",
"gggg",
updateGrid, OnError);
The issue (without knowing the error that you are receiving) is most likely that you are trying to pass in multiple parameters types. WCF does not usually support and expects an object instead. Create a response class with your parameters and use that instead.
public class ResponseObject
{
public List<int> recordIds { get; set; }
public string columnNameToUpdate { get; set; }
public string columnValue { get; set; }
}
Use this object as your parameter
public bool BatchUpdateRecords(ResponseObject responseObject)
{...

Dynamically create JS file using ASP.net Handler

I have many clients I want to give them scripts so I want to Create JS file based on their Cusotmer ID.
So I can return and it directly execute on customer side.
Client can be anyone either PHP,Html, ASP.net
Problem is when i browse this link it give me JS string but on customer side this script is not executing like for testing I put alert this alert is not showing on customer side
Customer
<head>
<script src="http://localhost:12604/JSCreator/Handler.ashx?CustomerID=123" type="text/javascript"></script>
<title></title>
</head>
Handler file
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string CustomerId = context.Request["CustomerId"].ToString();
string jscontent = JSFileWriter.GetJS(CustomerId); // This function will return my custom js string
context.Response.ContentType = "text/javascript";
context.Response.Write(jscontent);
}
public bool IsReusable
{
get
{
return false;
}
}
}
ContentType should be application/javascript
public void ProcessRequest(HttpContext context)
{
string CustomerId = context.Request["CustomerId"].ToString();
string jscontent = JSFileWriter.GetJS(CustomerId); // This function will return my custom js string
context.Response.ContentType = "application/javascript";
context.Response.Write(jscontent);
}

Categories