How to update value on input change in JSP? [duplicate] - javascript

I have session key that is a JavaScript variable which I got from a REST API call. I need to call my Java code in a servlet and pass that key as a parameter. What JavaScript function can I use to do that?

Several ways:
Use window.location to fire a GET request. Caveat is that it"s synchronous (so the client will see the current page being changed).
window.location = "http://example.com/servlet?key=" + encodeURIComponent(key);
Note the importance of built-in encodeURIComponent() function to encode the request parameters before passing it.
Use form.submit() to fire a GET or POST request. The caveat is also that it"s synchronous.
document.formname.key.value = key;
document.formname.submit();
With
<form name="formname" action="servlet" method="post">
<input type="hidden" name="key">
</form>
Alternatively you can also only set the hidden field of an existing form and just wait until the user submits it.
Use XMLHttpRequest#send() to fire an asynchronous request in the background (also known as Ajax). Below example will invoke servlet"s doGet().
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/servlet?key=" + encodeURIComponent(key));
xhr.send(null);
Below example will invoke servlet"s doPost().
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://example.com/servlet");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("key=" + encodeURIComponent(key));
Use jQuery to send a crossbrowser compatible Ajax request (above xhr code works in real browsers only, for MSIE compatibility, you"ll need to add some clutter ;) ).
$.get("http://example.com/servlet", { "key": key });
$.post("http://example.com/servlet", { "key": key });
Note that jQuery already transparently encodes the request parameters all by itself, so you don"t need encodeURIComponent() here.
Either way, the key will be just available by request.getParameter("key") in the servlet.
See also:
How to use Servlets and Ajax?
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript

No JavaScript function per se, but browsers usually* provide an XMLHttpRequest object and you can go through that.
Libraries such as YUI and jQuery provide helper functions to simplify its usage.
* for a value of "usually" that includes pretty much any browser that supports JavaScript and was released since Netscape 4 died

When sending POST add header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
The code looks like
Client:
function executeRequest(req) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("response").value = xhttp.responseText;
}
};
xhttp.open("POST", "execute/cardbrowser", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lorem=ipsum&name=binny");
}
Server:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("lorem"));
}

Related

Adblocker blocks XMLHttpRequest

I understand the fact, that adblockers try to deny loading (image) data later on. Anyway, I want to send some data to a php script (/log.php) to save it in a sql database. So in fact I don't care about the responsetext. This is my current js function I use to call the php script:
function log(id, unix_ms, frameid, eventtype, targetid, value){
var parameters = "";
parameters = parameters.concat("id=", encodeURI(id), "&unix_ms=", encodeURI(unix_ms), "&frameid=", encodeURI(frameid), "&eventtype=", eventtype, "&targetid=", targetid, "&value=", value);
var httprequest = new XMLHttpRequest();
httprequest.open("POST", "/scripts/log.php", true);
httprequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
httprequest.onreadystatechange = function() {
if(httprequest.readyState == 4 && http.status == 200) {
console.log(httprequest.responseText);
}
}
httprequest.send(parameters);
}
What can I change to pass the adblocker? I mean facebook uses things like ajax in masses to load text and even images in the timeline.
Is there maybe a way to use frames in the background since I don't care about the answer?
After analysing the log as suggested in a comment I found out that log.php seems to be in the blocklist, even if it's on the same server. So name you php files a little more complex to avoid this.
log.php -> submitlog.php

Understanding of ajax complete call

I'm struggling with stabilizing Selenium automation for jQuery/AJAX application hence referred to
https://www.swtestacademy.com/selenium-wait-javascript-angular-ajax/
and it has ajaxComplete() method which has following code -
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open('GET', '/Ajax_call', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send();
);
I haven't work on JavaScript before and this code which I'm not able to understand completely. I've following questions with this, if someone can help to understand it -
What is Ajax_call in this? Is it generic call to check ajax completion? Or do I need to have my own endpoint there? If yes, does single end point enough or do I need to identify all calls and add them in the method?
Please check the documentation for XMLHttpRequest.open. If you do, you will the second argument listed is
url
A DOMString representing the URL to send the request to.
This means that it is simply the URL you want to request. I can be anything you want. The / prefix means that you are request relative to the root of the website (so if you are requesting from https://example.com/somedir/somepage the request will be made to https://example.com/Ajax_call.

post http request to 3rd party server and get response with redirect

I have asp.net mvc project with form I need to send as httpRequestObject.
I'm trying for few days already to make simple XMLhttp request to 3rd party Credit card clearing company url and get back the response with redirect which on XML format - I don't care if redirection made by iframe or popup
checked all over the internet for solutions, tried it on JavaScript - but as far as I understood I'm not able to do it with JS, tried asp.net and c# also but nothing works for me.
checked all solutions here but still nothing work.
checked if I'm blocked in any way like proxy or firewall, and it's not the issue.
My current JS code is -
function createMPITransaction() {
var terminal_id = "0962832";
var merchant_id = "938";
var user = "my-user";
var password = "my-password";
var url="https://cguat2.creditguard.co.il/xpo/Relay";
var xmlStr = "my string";
var http = new XMLHttpRequest();
http.open("POST",url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader('Access-Control-Allow-Headers', '*');
http.setRequestHeader('withCredentials', true);
http.setRequestHeader('responseType', 'text');
var response = http.responseText;
http.onreadystatechange = function () {//Call a function when the state changes.
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
console.log(xmlStr);
console.log(http);
http.send(xmlStr);
and getting this from console -
XMLHttpRequest {readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: ""…}
Am I be able to do it on JS?
If not, how could I do it on asp.net c#?
the limitation of request to 3rd party server, and get redirection is not common and make it real challenge.
As far as just the code for redirection is concerned, you can look at similar answer, like for example: https://stackoverflow.com/a/3836811/6298965
What you may be still missing is to check if your request is specification compliant or you're actually getting an error so you're not redirected.
After an initial analysis, I guess that a jsonxml is likely needed for the api call.
Moreover it'd be better if you use or at least look at a github implementation: https://github.com/mderazon/creditguard-node/blob/master/lib/creditguard.js

Append something always to an XHR Request

I want to attach a JS Variable to every XHR request that will be issued from my single page web application.
What would be the best approach to achieve this? I don't want to establish special methods for sending with this attributes, as there may be third parties integrating with my application.
I thought about overriding the send method on the XHR Object but thats not considered good style either.
I can't use cookies due to requests being cross-domain.
Any better idea or approach to this?
Thank you!
-Alessandro
if you really want to extend the existing functionalities without adding any library-like function, you could solve this using monkey patching:
(function() {
var originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
var getParameter = 'foo=bar';
if(url.indexOf('?') === -1) {
url = url + '?' + getParameter;
} else {
url = url + '&' + getParameter;
}
console.log('you just got monkey-patched! url is now:', url);
originalOpen.call(this, method, url, async, user, password);
}
})();
var request = new XMLHttpRequest();
request.open('get', 'http://google.com');
see also this jsfiddle for a working example.
you can use the same technique when injecting stuff into the body of a request if you patch the send() function.
if you do, ensure you take care for the type of the data to be transmitted (see MDN). it doesn't make sense to append a parameter to a binary body ;)

Simplest way to write this AJAX call

I need to send an ajax request to a webserver "http://examples.com/ajax" the response will be the html of a <div> and it will be inserted to an existing <div id="holder">. What's the simplest, smallest way to write this in javascript? without using jQuery?
It only needs to support the latest version of chrome.
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
alert(req.responseText);
}
}
req.open("GET","http://examples.com/ajax.php",true) //true indicates ASYNCHRONOUS
req.send(null);
This solution uses get, so you've got to add variables using ? and & to your URL (e.g. http://examples.com/ajax.php?foo=bar&blah=blee.
If you want to do it using post, run a few with get and then this article is useful.

Categories

Resources