I need to convert a variable from JavaScript into a Java variable. I'm asking users for their e-mail ids with a Block-UI popup through Test Box. If the field is neither null nor empty, the e-mail id should be sent to a session variable so that it can be accessed anywhere in the project.
Here's my code:
function sbtEmail(){
var email = document.getElementById("EmailId").value;
if (email == null || email == ""){
alert("Enter your contact Email address to continue...!");
document.getElementById("EmailId").focus();
} else {
<%session.setAttribute("quoteEmail",email);%>
window.location.href = "demo2.jsp";
}
}
It doesn't work. What am I doing wrong?
You can not set a variable in the session (which resides on the server alone!) directly from JavaScript. You have to pass them to your server in some kind of request, and then the server can set it in the session.
Solved : using Ajax will solve the Problem.
<script type="text/javascript" src="../ajax.js"></script>
<script type="text/javascript">
function sbtEmail(){
var email = document.getElementById("anonymousEmailId").value;
if (email==null||email==""){
alert("Enter your contact Email address to continue...!");
document.getElementById("anonymousEmailId").focus();
}else{
enqueue("demo1.jsp?Id="+email,ajaxReplay);
}
}
function ajaxReplay(){
window.location.href="demo.jsp";
}
</script>
In demo1.jsp : set value for session variable
String Email = request.getParameter("Id");
session.setAttribute("sessEmail",Email);
Use this Ajax file:----> eval(function(p, a, c, k, e, r) { e = function(c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) r[e(c)] = k[c] || e(c); k = [function(e) { return r[e] } ]; e = function() { return '\\w+' }; c = 1 }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p } ('d 7;f n(a,b,c){6(!7)7=j s;6(!7.n(a,b,c))g l;6(!7.k)7.o();g h}f s(){3.5=j t();3.8=9;3.k;3.m=h;3.n=f(a,b,c){u(d i=0;i<3.5.p;i++)6(3.5[i][0]==a&&3.5[i][1]==b&&3.5[i][2]==c)g l;6(3.8==9){3.k=l;3.m=h;3.8=0}v{++3.8}3.5[3.8]=j t();3.5[3.8][0]=a;3.5[3.8][1]=b;3.5[3.8][2]=c;6(3.k&&c)w(c);g h};3.o=f(){6(3.8==9||3.5.p==0)g;3.k=h;6(3.m){d r=q();d a;6(r){u(d i=0;i<3.5.p;i++){6(3.5[i][2])w(3.5[i][2])}}3.m=l}3.x(3.5[0][0],3.5[0][1])};3.x=f(a,b){d r=q();6(r){r.E("F",a,h);r.G=f(){6(r.H==4){6(b)b(r.I);7.5.J(0,1);7.8>0?--7.8:7.8=9;6(7.8==9){7.k=l;7.m=h;g}v{7.o()}}};r.K(9)}}}f q(){d A=9;y{A=j z("L.B")}C(e){y{A=j z("M.B")}C(N){A=9}}6(!A&&O D!="P"){A=j D()}g A}', 52, 52, '|||this||queue|if|g_q|position|null||||var||function|return|true||new|isProcessing|false|callPreFunctions|enqueue|process|length|getXMLHTTP||ajaxQueue|Array|for|else|eval|getAjaxQueueResult|try|ActiveXObject||XMLHTTP|catch|XMLHttpRequest|open|GET|onreadystatechange|readyState|responseText|splice|send|Msxml2|Microsoft|oc|typeof|undefined'.split('|'), 0, {}))
Related
So I have a program that basically allows two users two chat back and forth and do other things via websocket with javascript and java server endpoints. When one of the users presses a button I have a listener that fires off a message to the other user which invokes a function. During this function I want to be able to call an AJAX POST with JQuery to update my database but this is causing a java.util.concurrent.TimeoutException. Any idea why this occurs? I imagine it has something to do with the fact that the websocket connection doesn't stay open long enough for the ajax call to go through.
So I've done the research and I've seen that websocket and AJAX are not exactly something that should be mixed (I think). However I can't seem to figure out an alternative even to update my database. There is a lot of code for this so I will try and only post the important parts.
Here is the part of the code for when the button is pressed (it is an agree button so both users must have pressed it hence the '**' and '--' characters).
fAgree.addEventListener("click", function() {
// selects this button
if (aStr == "**" && (yStr == "**" || oStr == "**")) {
if (fStr == "--") {
fStr = "*-";
//redirect to another page
} else if (fStr == "-*") {
fStr = "**";
if(secondTransaction == false) {
var firstCoordUpload = document.getElementById("yourPos").innerHTML;
var secondCoordUpload = document.getElementById("othersPos").innerHTML;
var firstLatUpload = parseFloat(firstCoordUpload.split(",")[0]);
var firstLonUpload = parseFloat(firstCoordUpload.split(",")[1]);
$.ajax({
url: "../../309/T11/setSaleData/" + getURLParameter("saleID") + "/" + firstLatUpload + "/" + firstLonUpload + "/" + firstCoordUpload + "/" + secondCoordUpload + "/" + secondSeller,
type: "POST",
headers: {
"Authorization" : getCredentials(),
},
success: function (result) {
window.location.href = '../../frontEnd/profilePage/index.html?username='+ getUsername();
console.log(result);
},
error: function (dc, status, err) {
console.log(err);
console.log(status);
}
});
}
}
agreeBut.socket.send("a,f");
htmlChange(fStr, fStar);
}
});
Here is the part of the code that is called at the end of the code above (the agreeBut.socket.send()).
agreeBut.socket.onmessage = function(message) {
// check [0]: a for agree buttons,
// m for map,
// l of location buttons,
// t for trade
var mess = message.data.split(",");
if (mess[0] == "a") {
// second a shows the agree button was pressed, changes aStr
// accordingly and displays
if (mess[1] == "a") {
if (aStr == "--") {
aStr = "-*";
} else if (aStr == "*-") {
aStr = "**";
}
htmlChange(aStr, aStar);
// shows the final agree button has been pressed, changes fStr
// accordingly and displays
} else if (mess[1] == "f") {
if (fStr == "--") {
fStr = "-*";
//redirect
} else if (fStr == "*-") {
fStr = "**";
alert("on this");
if(secondTransaction == true) {
alert("doing it");
var firstCoordUpload = document.getElementById("yourPos").innerHTML;
var secondCoordUpload = document.getElementById("othersPos").innerHTML;
var firstLatUpload = parseFloat(firstCoordUpload.split(",")[0]);
var firstLonUpload = parseFloat(firstCoordUpload.split(",")[1]);
$.ajax({
url: "../../309/T11/setSaleData/" + getURLParameter("saleID") + "/" + firstLatUpload + "/" + firstLonUpload + "/" + firstCoordUpload + "/" + secondCoordUpload + "/" + secondSeller,
type: "POST",
headers: {
"Authorization" : getCredentials(),
},
success: function (result) {
console.log(result);
alert("Got it");
window.location.href = '../../frontEnd/profilePage/index.html?username='+ getUsername();
},
error: function (dc, status, err) {
console.log(err);
console.log(status);
}
});
}
//window.location.href = '../../frontEnd/profilePage/index.html?username='+ getUsername();
}
htmlChange(fStr, fStar);
}
}
};
It turns out I was getting this problem because of the timeout that was set on my java ServerEndpoint. In the class I used the setMaxIdleTimeout(0) function on the session variable to have no idle timeout. This seemed to solve my problem (however I feel like this is really just a workaround for poor websocket and ajax implementation on my end).
Ive got my Parse SDK set up, and the "Hello World!" function runs fine. Im trying to now send two int's (i1 & i2) and return the sum. What I need to know is:
1) How to send variables
2) How to receive them. As changing the HashMap from HashMap<String,Object> to HashMap<Integer,Object> gives an error
ParseCloud function (js)
Parse.Cloud.define("add", function(request,response)
{
var intA = 1;
var intB = 2;
var intC = intA + intB;
//var s = "Hello Add!";
//response.success(s);
response.success(intC);
});
Android method, doAddition()
s1 = et1.getText().toString();
s2 = et2.getText().toString();
i1 = Integer.parseInt(s1);
i2 = Integer.parseInt(s2);
ParseCloud.callFunctionInBackground("add", new HashMap<Integer, Object>(), new FunctionCallback<Integer>()
{
#Override
public void done(Integer sum, ParseException e)
{
s3 = sum.toString();
et3.setText(s3);
}
});
The above Android-method gives an error:
The method callFunctionInBackground(String, Map<String,?>,
FunctionCallback<T>) in the type ParseCloud is not applicable for the
arguments (String, HashMap<Integer,Object>, new
FunctionCallback<Integer>(){})
set your args correctly before the call to your Cloudfunction ( as proper javascript parms ) then get them in the cloud funct...
var mathArg1 = request.params.arg1;
var mathArg2 = request.params.arg2;
create a result field in JS...
var mathResult = mathArg1 + mathArg2;
return the result to client as JSON ( get used to this in cloud interfaces! )
success: function(user) {
response.success(mathResult.toJSON());
},
I've been using rhino to allow the customization of some applications. Here is an example of JavaScript function that is called from Java:
function() {
var phone = this.telephoneNumber;
phone = phone.replace(/[^+0-9]/g,"");
if (phone.indexOf("+") == 0) {
phone = "00" + phone.substring(1);
}
if (phone.indexOf("0041") == 0) {
phone = "0" + phone.substring(4);
}
if (phone.indexOf("0") == 0) {
phone = "0" + phone;
}
return {
Name: this.sn + " " + this.givenName,
firstName: this.givenName || "",
lastName: this.sn || "",
phone: phone,
service: "",
info: ""
};
}
The java application can then get the values of the returned object for whatever it needs to do.
Now that rhino is part of the JVM, I would like to use the scripting API instead of the Rhino API, but I haven't found how to get the field values of a JavaScript object from Java code.
This loosely couples the scripting language, but with the caveats that the functions need to be named, and the returned object needs to be a Map (Rhino does this, but I'm not sure about JRuby).
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval("function x() { return { foo: 10 } }");
Object o = ((Invocable)engine).invokeFunction("x");
if (o instanceof Map) {
Map m = (Map<Object, Object>)o;
System.out.println(m.get("foo"));
}
or
CompiledScript script = ((Compilable)engine).compile("(function() { return {bar:20} })()");
System.err.println(((Map)script.eval()).get("bar"));
But you have to cheat and call your function by padding it with (...)().
I have the unenviable task of editing a 2000 line javascript file inorder to maintain and add some new feature to a web app written in JSP, Json-RPC, jQuery and Java. I do not possess any deeper knowledge of jQuery and Json-RPC except basic Javascript knowledge and the original developer is not there anymore.
There is a JS function which accepts a few params, and calls a Json-RPC and here I am getting the error
arg 1 could not unmarshal
Can someone please tell me what this error means?
Here is my code
function distributeQuantityNew(pReportId, pDecimalPlaces, pRun) {
try {
alert('distributeQuantityNew: ' + pReportId + ', ' + pDecimalPlaces + ', ' + pRun);
var fieldValue = $("#distribution_quantity_" + pReportId).val();
if (fieldValue.length == 0) {
showErrorDialog(resourceBundleMap["error.no.distribution.quantity"]);
return;
} else {
$("#distribution_quantity_" + pReportId).val("");
}
var affectedRowIds = [];
var rows = $("#tableBody_" + pReportId + " tr:visible").has("input[type=text]").filter(function(index) {
var voucherType = this.cells[getVoucherColumnIndex()].innerHTML;
if ((voucherType == 'TRANSFER_CS') || (voucherType == 'PAYOUT_CS') || (voucherType == 'SOURCE_BON') || (voucherType == 'PAYOUT_BON')) {
return false;
}
affectedRowIds.push(parseInt(this.id.split("_")[3]));
return true;
}
);
var affectedReportRows = $.extend(true, {}, foreignReportMap[pReportId]);
$.each(affectedReportRows.map, function(i, row) {
if ($.inArray(row.partnerReportBillNr, affectedRowIds) == -1) {
delete affectedReportRows.map["row_" + row.partnerReportBillNr];
}
});
var report = getLoadedReportByRunId(pReportId);
var productType = report.partnerProductType;
SessionManager.extend();
var resultRows = jsonrpc.foreignReportObject.distributeQuantity(affectedReportRows, fieldValue, pDecimalPlaces, pRun);
alert('back after RPC');
$.each(resultRows.map, function(i, row) {
foreignReportMap[pReportId].map["row_" + row.partnerReportBillNr] = row;
updateForeignReportRow(row, true, productType);
});
updateSummaryRow(pReportId);
toggleApproveAllLink(pReportId);
sortForeignReportTable(pReportId, true);
} catch (e) {
handleError("Failed to distribute quantity: ", e);
}
}
I have peppered it with alerts so that I know whether RPC call was succesful, but I get the error arg 1 could not unmarshal before that from the catch block. Thanks for any hints
OK, got it solved. The first parameter to the remote function is expecting a list of Map<String, SomeBO>. SomeBO is a bean with several BigDecimals. I had another JS function which had set the values passed into the Map. This function was setting a BigNumber where I had a setter of String only. I wish the error I had gotten back from JSON unmarshaller was a bit more descriptive...Below is the code where I added .toString() to solve the issue
foreignReportMap[pReportId].map["row_" + pRowId].clientQuantity = clientQuantity.toString();
foreignReportMap[pReportId].map["row_" + pRowId].totalClientQuantity = totalClientQuantity.toString();
I'm currently creating an ArrayList in Java, then running the .toJson function from Google-gson on it:
public String statusesToJson(ArrayList<String> statuses){
Gson gson = new Gson();
return gson.toJson(statuses);
}
Which results in the JSON:
[ "u", "u", "u", "u" ]
Then in JSP I'm passing it into JavaScript:
<script language="JavaScript" type="text/javascript">CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', '<%=model.arrayListToJson(model.getStatuses()) %>');</script>
Then in the JavaScript I'm parsing it to a JSON array:
CheckStatus.statuses = JSON.parse(statuses);
alert(CheckStatus.statuses);
This then results in the following output:
u, u, u, u
The problem is that the following doesn't work and causes my page to not load:
alert(CheckStatus.statuses[0]);
What's wrong with this?
EDIT:
Loaded Function:
loaded : function(guid, context, statuses) {
CheckStatus.guid = guid;
CheckStatus.context = context;
CheckStatus.statuses = JSON.parse(statuses);
alert(CheckStatus.statuses[0]);
if(CheckStatus.init == null){
submitForm('checkStatusForm', CheckStatus.guid);
CheckStatus.init = true;
}
setupForm('checkStatusForm', function(){CheckStatus.validStatus();});
//CheckStatus.setImages();
applyCSS3('Check_Status');
}
Valid Status Function:
validStatus : function(){
CheckStatus.params = $('#checkStatusForm').serializeObject();
if(document.getElementById('regionID').value != "" && document.getElementById('regionAction').value != ""){
submitForm('checkStatusForm', CheckStatus.guid);
}else{
error("Cannot Commit", "You must select an action before attempting to commit.");
}
},
Setup Form Function:
/**
* Sets up the form to submit when the user presses enter inside an input
* element. Also calls the callback when the form is submitted, does not
* actually submit the form.
*
* #param id The id of the form.
* #param callback The callback to call.
* #return Nothing.
*/
function setupForm(id, callback) {
$('#' + id + ' input').keydown(function(e) {
if (e.keyCode === 13) {
$(this).parents('form').submit();
e.preventDefault();
}
});
$('#' + id).submit(function(e) {
e.preventDefault();
callback();
});
}
Submit Form Function:
/**
* Serializes and submits a form.
*
* #param id
* The id of the form to submit.
* #param guid
* The guid of the page the form is on to pass to the server.
* #return nothing.
*/
function submitForm(id, guid) {
var subTabId = $('#' + id).closest('#tabs > div > div').attr(
'id'), tabId = $('#' + id).closest('#tabs > div')
.attr('id'), data = $('#' + id).serializeArray();
data.push( {
name : "framework-guid",
value : guid
});
$.ajax( {
type : 'POST',
cache : 'false',
url : '/pasdash-web/' + tr("_", "", tabId.toLowerCase()) + '/' + tr("_", "", subTabId)
+ '.jsp',
data : data,
success : function(html) {
$('#' + subTabId).html(html);
resourceChanged(tabId, subTabId,
$('#' + id + ' input[name="framework_command"]')[0].value,
guid);
},
error : function(jqXHR, textStatus, errorThrown) {
error('Ajax Error', textStatus);
}
});
return false;
}
You don't need to wrap your JSON with strings, that will just force you to have to reparse it. I would try removing those quotes and not calling JSON.parse
loaded : function(guid, context, statuses) {
CheckStatus.guid = guid;
CheckStatus.context = context;
// Here's the change
CheckStatus.statuses = statuses;
alert(CheckStatus.statuses[0]);
And change your HTML to be
<script type="text/javascript">
CheckStatus.loaded('<%=model.getPageId() %>',
'<%=request.getContextPath() %>',
// the following line should output something like
// ["a", "b"]
// which is perfectly valid JavaScript
<%=model.arrayListToJson(model.getStatuses()) %>);
</script>
You should be able to write:
CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', <%=model.arrayListToJson(model.getStatuses()) %>);
without the quotes around the last argument. Then, that "loaded()" function will get the object directly and there'll be no need to call "JSON.parse()".
Check the type of the result of JSON.parse (). Seems to me that it is a string and not an array. Maybe a pair of quotes somewhere that should not be there?