How to use AJAX in Java? [duplicate] - javascript

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
I have the following javaScript function:
function loadSomething() {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "javaservlet.java", true);
xhttp.send();
}
and I want to get, lets say an int value from a Java Servlet - "javaservlet". What code should I write in javaservlets doGet() method in order to send a value, so I can get and use it in javaScript? Thank you!

So, you want to return something from your servlet back to the javascript you called that servlet from. Here is the way, make an XMLHttpRequest object using these lines of code
var reqObject = new XMLHttpRequst(); or new ActiveXObject("Microsoft.XMLHTTP");
now make a request to the servlet's get or post method using the XMLHttpRequst's open method, you can simply do it like this
reqObject.open("GET/POST", "ServletName", true);
now if you have made a request to the server and state of the object reqObject is being changed then you will want to see the changes that are being made. Call a function when the state of the object is changed
reqObject.onreadystatechange = processRespose;
if you want to send something as parameter to the servlet use send method otherwise send null.
reqObject.send(null);
now if the servlet is returning something in the method you called from .open the state of the object will be changed and function processResponse will be called.
function processResponse(){
//check whether the response form the server is intact and correct
if(reqObject.status==200 && reqObject.readyState==200){
//simply means we got the response correctly
//Now you can get the response by
var res = reqObject.responseText;
}
}
you can read about the objects methods and properties here
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
I java servlet you just have to send the expected string with the PrintWriter's object. A rough version of Get method would look somewhat like this
doGet(request, response){
PrintWriter out = response.getWriter();
out.println("Javasrvlet");
}

You need to provide url mapping for that servlet in web.xml. I am assuming your servlet class name is JavaServlet.
<servlet>
<description></description>
<display-name>JavaServlet</display-name>
<servlet-name>JavaServlet</servlet-name>
<servlet-class>JavaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JavaServlet</servlet-name>
<url-pattern>/javaServlet</url-pattern>
</servlet-mapping>
Now change the following in javascript code to send GET request to JavaServlet.
function loadSomething()
{
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "javaServlet", true);
xhttp.send();
}

You can write like this....
public void service(HttpServletRequest request, HttpServletResponse){
response.getWriter().write("<Your Data>");
}

Related

producing a GET response to an ajax POST

In javascript I am POSTing with ajax and I need to get a reply from my Python program. The following code shows the javascript, but how does I produce the desired responseText from a GET on the Python side?
In this example I am want a Yes or No reply to a question for the user as to whether to change the name provided or not.
I understand how to receive the name and value in the python POST, but I don't know how to produce the response in the associated python GET.
function changeName(name,value){
var json = '[{';
json += '"name":"'+name+'",'
json += '"value":"'+value+'"}]'
loadDoc(json,"edit")
}
function loadDoc(data,url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", ("/"+url), true);
xhttp.setRequestHeader("Content-type", "text"); #or something
xhttp.send(data);
}
My typical response in Python GETs follows one of the following 2 patterns, but neither seems to allow me to reply in this case.
self.response.out.write(template.render( template_values))
return webapp2.redirect("/templatename/%s" % variable)
(No PHP or jquery, please.)

ScriptEngineManager: How to make a http request from JavaScript Engine

I'm, using javax.script.ScriptEngineManager, in which, im using the JS Script Engine, like this.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.eval(str);//str contains JS code as String
Invocable inv = (Invocable) engine;
Object[] objAry = {"Sample String input"};//input ary
Object objOutput = inv.invokeFunction(fuctionName, objAry);//function name & input ary
Now, I want to execute, JS code which will make a HTTP request.
Currently, I'm trying with this script.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
But, it is not supported, as I guess, this code, is for browser.
Therefore, My question is, How to make a HTTP call from JS code, which is executing via javax.script.ScriptEngineManager?
And, currently, I'm using jdk7.

Load external URL content using pure Javascript

The following JQuery gets content of an external url:
var url = 'example.com/editor/stores/10';
$('#storeArticlePublish_Channel').load(url);
I do not want to use JQuery. How would I do this using normal javascript?
You can use XMLHttpRequest object for this.To make a request:
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET",URL,true);
xmlhttp.send();
The 'URL' is the url you want to execute/open.
The 3rd parameter is for async request, it can be either true or false.
And to get the result in #storeArticlePublish_Channel element, you can simply use this in the next line:
document.getElementById("storeArticlePublish_Channel").innerHTML = xmlhttp.responseText;

parse rss feed using javascript

I am parsing an RSS feed using PHP and JavaScript. First I created a proxy with PHP to obtain the RSS feed. Then get individual data from this RSS feed using JavaScript. My issue with with the JavaScript. I am able to get the entire JavaScript document if I use console.log(rssData); with no errors. If I try to get individual elements within this document say for example: <title>, <description>, or <pubDate> using rssData.getElementsByName("title"); it gives an error "Uncaught TypeError: Object....has no method 'getElementsByName'". So my question is how to I obtain the elements in the RSS feed?
Javascript (Updated)
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
return xmlHttp.responseXML;
}
// rss source
var rssData = httpGet('http://website.com/rss.php');
// rss values
var allTitles = rssData.getElementsByTagName("title"); // title
var allDate = rssData.getElementsByTagName("pubDate"); // date
Try changing the last line of the httpGet function to:
return xmlHttp.responseXML;
After all, you are expecting an XML response back. You may also need to add this line to your PHP proxy:
header("Content-type: text/xml");
To force the return content to be sent as XML.

How can I access the plain text loaded in an <iframe> on IE?

I have an <iframe> whose src points to a plain text file (not HTML). The text gets loaded and displayed on screen, but seems to be hidden to JavaScript.
In other browsers, iframe.contentWindow.document.body.innerText is enough to get it for you, but IE returns an empty string in that case.
Is there a way that IE can access the text inside the file without involving a server?
You can read this file using XmlHttpRequest. If the browser can read it, so can XmlHttpRequest.
/* Read a file using xmlhttprequest
If the HTML file with your javascript app has been saved to disk,
this is an easy way to read in a data file. Writing out is
more complicated and requires either an ActiveX object (IE)
or XPCOM (Mozilla).
fname - relative path to the file
callback - function to call with file text
*/
function readFileHttp(fname, callback) {
xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", fname, true);
xmlhttp.send(null);
}
/*
Return a cross-browser xmlhttp request object
*/
function getXmlHttp() {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp == null) {
alert("Your browser does not support XMLHTTP.");
}
return xmlhttp;
}
Call the readFileHttp(fname, callback) using the iframe.src property for the fname parameter.
The callback parameter should be a function that does whatever you want with the result.
Something like this:
var myIFrame = document.getElementById('iframeIdGoesHere');
readFileHttp(myIFrame.src, function(result){
//process the result
});
EDIT based on comment and edit in question:
It might be that body is not available as a js property on the document. You could try:
iframe.contentWindow.document.getElementsByTagName('body')[0].innerText
My original answer (kept only as reference because of the comment):
You
say in a comment that you pull the
path from an <input type='file' />.
You can use that to upload the file to
the server, and then read it using
simple file reading mechanisms. (after
all, the <input type='file' /> is
meant for server uploads...)
Just a shot in the dark, but have you tried the innerHTML property?
Alternatively, the more "proper" way to do this is to request the file directly with XMLHttpRequest.
and
window.frames[0].document.getElementsByTagName("body")[0].innerHTML
?

Categories

Resources