invoke Java Servlet doGet method from JavaScript code - javascript

I want to ask which code I need to write in order to invoke a doGet() in a Java Servlet. Right now the code I had written is:
function(){
var sURL = getUniqueSid("http://localhost:8080/Test/Sample?F=" + f + "&FB=" + fb);
var ret = xmlSyncHttpReq(sURL);
if (ret){
var params = new GG_ContainerParams("General");
var xTarget = params.dataSource;
var xElms = ret.selectNodes("Param");
for (var i=0;i<xElms.length;i++){
var x = xElms(i).cloneNode(true);
var chk = xTarget.selectSingleNode("Param[#Name = \"" + x.getAttribute("Name") + "\"]");
if (chk)xTarget.replaceChild(x,chk);
else xTarget.appendChild(x);
params.redraw();
}
}
function xmlSyncHttpReq(sURL,xmlSend,doThrow){
try{
var xmlhttp = new XMLHttpRequest();//ActiveXObject("Microsoft.XMLHTTP");
sURL = getUniqueSid(sURL);
xmlhttp.Open("GET", sURL, false);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
if (typeof(xmlSend) == "object" && xmlSend != null)xmlSend = xmlSend.xml;
xmlhttp.Send(xmlSend);
if(xmlhttp.responseXML.documentElement){
if (checkErrors(xmlhttp.responseXML))return false;
else return xmlhttp.responseXML.documentElement;
}
xmlhttp = null;
return false;
}catch(e){
if (doThrow)throw e;
else alert(e.description);
return false;
}
}
Thanks in advance,
Tal Tchernihovski.

Pay attention to the JavaScript console in the browser. You should have seen the following error:
Uncaught TypeError: Object #<XMLHttpRequest> has no method 'Open'
JavaScript follows the Java naming conventions, not C# naming conventions. Methods start with lowercase. You need to use open() and send() instead of Open() and Send().
See also:
XMLHttpRequest documentation

Related

How can I solve my problem posting number sign to make a hashtag?

I'm trying to post # sing to make some words turn to hashtags but the code doesn't work and it's via API using this code:
true == function()
{
var getMyItem = function (str)
{
if (sessionStorage.getItem(str) == null)
{
setMyItem(str, 0);
return 0;
}
return sessionStorage.getItem(str);
}
var setMyItem = function (key, value)
{
sessionStorage.setItem(key, value);
}
function bot(post)
{
const Http = new XMLHttpRequest();
var Token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Token
var ID= "xxxxxx";
var url= 'https://bot.xxx/api/'+Token+'/sendMessage?text='+post+'&chat_id='+ID;
Http.open("GET", url);
Http.send();
}
// you need to change the url variable contents for your own Telegram API or those of the same SN APIs..
So when it comes to call the post like with this code:
var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
var post_n = "%23Hi. It's: " + myDate + "\n";
var post = encodeURI(post_n);
if (getMyItem(key + "htr") != "yes")
{
bot(post);
setMyItem((key + "htr"),"yes");
}
return true;
}
}()
, it doesnt support # sign in my browsers including Chrome an Firefox and nothing is sent actually.
So if it were for Telegram, the bot would look like this (and I donno if it works or not but I'm talking about another SN):
var url= 'https://api.telegram.org/'+Token+'...
Please tell me how to send # code. By the way, "%23" doesn't work.

Looking for alternative of javscript eval function [duplicate]

This question already has answers here:
How do I include a JavaScript file in another JavaScript file?
(70 answers)
Closed 2 years ago.
I am using the following function to make an XHR request and execute javascript from the response if possible:
function ajaxRequest(resultDiv, processing, action, paramName, param, paramName2, param2, parseJs) {
if (processing) {
document.getElementById(resultDiv).innerHTML = processing;
}
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var resp = this.responseText;
document.getElementById(resultDiv).innerHTML = resp;
if (parseJs) {
parseScript(resp);
}
}
}
if (paramName2) {
xmlhttp.open("GET", "/query?" + paramName + "=" + param + "&" + paramName2 + "=" + param2 + "&action=" + action, true);
} else {
xmlhttp.open("GET", "/query?" + paramName + "=" + param + "&action=" + action, true);
}
xmlhttp.send();
}
function parseScript(strcode) {
var scripts = new Array();
while (strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
var s = strcode.indexOf("<script");
var s_e = strcode.indexOf(">", s);
var e = strcode.indexOf("</script", s);
var e_e = strcode.indexOf(">", e);
scripts.push(strcode.substring(s_e + 1, e));
strcode = strcode.substring(0, s) + strcode.substring(e_e + 1);
}
for (var i = 0; i < scripts.length; i++) {
try {
eval(scripts[i]);
} catch (ex) {
alert("Error while executing");
}
}
}
But I got to know that eval function is somehow dangerous and very slow. So can you help me to find something alternative of eval and rewrite the code snippet to work same way it meant to be but with alternative of eval? Thanks in advance, and sorry for my bad English.
An alternative to eval() might be to inject the code into a <script> tag on your page, upon which it is then immediately executed.
In the example below, the code is provided to script.text. For a URL as in your question, use script.src instead.
const script = document.createElement('script');
script.text = 'console.log("foo");';
document.body.append(script);
// logs "foo"
Eval can be slow but is as dangerous as any other solution if you are running code that is not trusted or verified by yourself. If you do need another way to run this you can try dynamic script text insertion as described in the answer here

Send multiple parameter in ajax request using javascript

So I want to use ajax request and I know how to use it.
But problem that i had that I want to pass parameters to request. So My first page had 4 parameter then I build url like this,
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
but now parameter is increasing like now I have 20 more. So now building url like this going to be messy approach. Is there a better way to do this.
Here is my function where i am building URL in javascript function.
function closeAssessment() {
var closeReason = document.getElementById("SectionClousureReason");
var closeReasonStr = closeReason.options[closeReason.selectedIndex].value;
var closeCmt=document.getElementById("SectionCloseAssessmentCmt").value;
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
ajaxRequest(url);
return;
}
edit:
As you ask here is my ajaxRequest function,
function ajaxRequest(url) {
strURL = url;
var xmlHttpRequest = false;
var self = this;
// Mozilla, Safari
if (window.XMLHttpRequest) {
self.xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
self.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpRequest.open("POST", strURL, true);
self.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xmlHttpRequest.onreadystatechange = function() {
if (self.xmlHttpRequest.readyState == 4) {
if (self.xmlHttpRequest.status == 200) {
var htmlString = self.xmlHttpRequest.responseText;
var parser = new DOMParser();
var responseDoc = parser.parseFromString(htmlString, "text/html");
window.close();
} else {
ajaxFailedCount++;
// Try for 1 min (temp fix for racing condition)
if (ajaxFailedCount < 1200) {window.setTimeout(function() {ajaxRequest(url)}, 50);}
else {alert("Refresh failed!")};
}
}
}
self.xmlHttpRequest.send(null);
}
You could make an object with the key/value pairs being what you want added to the URL.
var closeReason = document.getElementById("SectionClousureReason");
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true',
closeReasonStr: closeReason.options[closeReason.selectedIndex].value,
closeCmt: document.getElementById("SectionCloseAssessmentCmt").value
};
Then add them to the URL via a loop.
var url = "./ControllerServlet?";
var urlParams = Object.keys(params).map(function(key){
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
url += urlParams;
ajaxRequest(url);
Note: I added encodeURIComponent just to be safe.
EDIT: From your comment, it seems you want to submit a <form> but you want to use AJAX to do so. In that case, you can loop over the form elements and build the above params object.
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true'
};
var form = document.getElementById('yourForm'),
elem = form.elements;
for(var i = 0, len = elem.length; i < len; i++){
var x = elem[i];
params[x.name] = x.value;
}
Build up an object of your parameters and put them in the uri through a loop like this:
var values= {
page_id: 'BPCLA',
action: 'test'
},
uri_params = [],
uri = 'http://yoururl.com/file.php?';
for (var param in values) uri_params.push( encodeURIComponent( param ) + '=' + encodeURIComponent( values[ param ] ) );
uri = uri + uri_params.join( '&' );
console.log( uri );
Or consider using POST to transport your parameters, as many browsers have limitations on the query string.
Edit: you can also build yourself a function which traverses your form and builds up the values object for you so you don't have to do it manually.
Be aware however that anyone can inject custom url paramters simpy by appending form elements before submitting the form (by using the developer tools for example) so keep that in mind.
If you are using jQuery you can use .serializeArray() or have a look at this answer for a possible function you could use.

SCRIPT65535: Invalid calling object in IE9

I am new to javascript. I am facing an issue in someone else written code. They have created a security.js file and they are trying to overwrite xmlHTTPRequest (am not sure). attaching the code here.
(function () {
function getXHRObj(baseObj){
var Impl = function(){
this.onreadystatechange = null;
return this;
};
//Impl.prototype.onreadystatechange = null;
// set the prototype of the new constructor
Impl.prototype = baseObj;
//Impl.prototype.constructor = Impl; // does not work in IE
// the object to be returned
var retObj = new Impl();
function isHTTPReq(url){
if(url){
var colIndx = url.indexOf('://');
if((colIndx < 0)
|| (url.substr(0, colIndx).toLowerCase().indexOf('http') == 0))
return true;
}
return false;
}
// customize open to add token in URL
// even POST request should do this since POST may not always have key=value&... data format
retObj.open = function(method, URL, async, user, pwd){
if(isHTTPReq(URL)){
var prefix = (URL.indexOf('?') < 0)? '?' : '&';
URL += (prefix + window.csrfToken);
}
//alert('making ajax to - ' + URL);
Impl.prototype.open(method, URL, async, user, pwd);
};
// customize send
retObj.send = function(body){
/* Register the handler just before "send" to allow reuse of same object */
Impl.prototype.onreadystatechange = function(){
//alert('Impl.prototype.readyState- '+ Impl.prototype.readyState);
// copy the properties to return object
if(Impl.prototype.readyState)
retObj.readyState = Impl.prototype.readyState;
if(Impl.prototype.readyState == 4){
if(Impl.prototype.status)
retObj.status = Impl.prototype.status;
if(Impl.prototype.statusText)
retObj.statusText = Impl.prototype.statusText;
if(Impl.prototype.responseText)
retObj.responseText = Impl.prototype.responseText;
if(Impl.prototype.responseXML)
retObj.responseXML = Impl.prototype.responseXML;
//alert('xml done');
}
// publish event to return object handler
if(retObj.onreadystatechange){
//alert('invoking handler - \n' + retObj.onreadystatechange);
retObj.onreadystatechange();
}else{
//alert('no handler');
}
};
Impl.prototype.send(body);
};
// delegate other methods
/* Redefinition is necessary because IE does not allow inheritance
from native objects */
retObj.abort = function() {
Impl.prototype.abort();
};
retObj.setRequestHeader = function(hdr, val){
Impl.prototype.setRequestHeader(hdr, val);
};
retObj.getResponseHeader = function(hdr){
return Impl.prototype.getResponseHeader(hdr);
};
retObj.getAllResponseHeaders = function(){
return Impl.prototype.getAllResponseHeaders();
};
return retObj;
}
// redefine the XMLttpRequest to use custom definition
if(window.XMLHttpRequest){
var Base_XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function(){
//alert('in new XHR');
return getXHRObj(new Base_XMLHttpRequest());
};
}
// redefine the ActiveXObject to use custom definition
if(window.ActiveXObject) {
var Base_ActiveXObject = window.ActiveXObject;
window.ActiveXObject = function(objType){
//alert('in new ActiveXObj for - ' + objType);
if((objType.toLowerCase() != "microsoft.xmlhttp")
&&(objType.toLowerCase().indexOf("msxml2.xmlhttp") < 0)){
// return the standard impl for non-ajax objects
return new Base_ActiveXObject(objType);
}else{`enter code here`
//alert('returning new impl for ' + objType);
return getXHRObj(new Base_ActiveXObject(objType));
}
};
}
})();
This code is working fine in IE7 & 8, but this is giving error in all other browsers.
IE9 error -
SCRIPT65535: Invalid calling object
security.js, line 71 character 4
Error is pointing to this.onreadystatechange = null;
var Impl = function(){
this.onreadystatechange = null;
return this;
};
Appreciate immediate help.
Thanks!

IE8 is breaking my AJAX... FF is fine

Feeling very proud of myself after creating a form with an AJAX submit, I test it in IE8 and get "Message: 'quantity' is undefined". I've read that it could be something to do with the fact that earlier versions of IE used ActiveX for AJAX requests, but I'm very new to JS and have no real understanding of the problem, let alone the ability to implement a fix.
Here's my code:
var time_variable;
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
From your last comment on your question, I suspect you are not defining 'quantity' anywhere and assuming that it will reference the form field. Try this:
if(xmlhttp) {
var txtname = document.getElementById("txtname");
var quantity = document.getElementById("quantity");
var price = document.getElementById("price");
var store = document.getElementById("store");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
If quantity is a form field you need to get it using getElementById before using it just like you did with txtname:
var quantity = document.getElementById("quantity");
You cant use it directly from the form.

Categories

Resources