Pass Servlet variable to Javascript - javascript

I have a JSP page which I use to submit some data to a HTTPServelet. I need to show an alert after successfully completing task in servlet so I have a JavaScript AJAX function which executes in onSubmit event of JSP Page. but when I click submit button AJAX function does not execute with it.
Here is my Javascript function:
function alerts(servlet) {
var xhr = new XMLHttpRequest();
xhr.open("POST", servlet, true);
console.log("connected to "+servlet);
xhr.send(null);
xhr.onreadystatechange = function() { //this function does not execute
if (xhr.readyState === 4) {
if (xhr.status === 200) {
content = xhr.responseText;
var objects = JSON.parse(content);
console.log(objects);
var elemant = document.getElementById("tblObjects");
var child = elemant.children;
var childLength = child.length;
if (0 < child.length) {
for (i = 0; i < childLength; i++) {
deleteElamant("tblObj");
}
}
}
}
};
}
And my Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
//Do somethings inside Servlet
response.getWriter().write("my alert messege to JavaScript");
RequestDispatcher rd = request.getRequestDispatcher("/NextServlet");
rd.forward(request, response);
} catch (Exception ex) {
}
}

Related

send the request id with XMLHttpRequest to the serverside

Here I deployed the Get request with Id to pass from the client-side to the server-side to download excel file according to the Id.
client-side js file
$scope.getAUGFile = function () {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var params = JSON.stringify({ articleId: articleId });
var url = RESOURCES.USERS_DOMAIN + '/AUGFile/excelDownload/'
xhr.open("GET", url+"?"+params);
xhr.setRequestHeader("authorization", getJwtToken());
xhr.responseType = 'blob';
xhr.onload = function () {
if (this.status === 200) {
saveAs(xhr.response, "mvvAUGExcelTemplate.xls");
}
};
xhr.send(null);
};
server-side js file(spring boot)
#RequestMapping(value = "/AUGFile/excelDownload/{articleId}", method = RequestMethod.GET)
public ResponseWrapper excelGenerateAUG(HttpServletRequest request, HttpServletResponse response,#PathVariable Long articleId){
try{
fileService.downloadAUGFile(request,response,articleId);
return ResponseWrapper.successWithMessage(messageSource.getMessage("success_code",null, Locale.ENGLISH));
} catch (Exception e){
lOG.error(">> Excel file Download error", e);
return ResponseWrapper.failWithMessage(messageSource.getMessage("fail_code", null, Locale.ENGLISH));
}
}
When I execute the client-side function, In the serverside take the articleId value as NULL. How can I fix it? Any advice, help, pointers welcome!
first
console.log(articleId) inside your function to see if its defined and accessible to xhr to send
& try this this instead xhr.open("GET", url+articleId);
or try this
xhr.open("GET", url+"?articleId="+articleId);
I got the correct way of this! It is working now.
client-side js file
$scope.getAUGFile = function () {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var url = RESOURCES.USERS_DOMAIN + "/AUGFile/excelDownload/"+articleId;
xhr.open("GET", url);
xhr.setRequestHeader("authorization", getJwtToken());
xhr.responseType = 'blob';
xhr.onload = function () {
if (this.status === 200) {
saveAs(xhr.response, "mvvAUGExcelTemplate.xls");
}
};
xhr.send(null);
};
server-side js file
#RequestMapping(value = "/AUGFile/excelDownload/{articleId}", method = RequestMethod.GET)
public ResponseWrapper excelGenerateAUG(HttpServletRequest request, HttpServletResponse response,#PathVariable("articleId") String articleId){
try{
fileService.downloadAUGFile(request,response,articleId);
return ResponseWrapper.successWithMessage(messageSource.getMessage("success_code",null, Locale.ENGLISH));
} catch (Exception e){
lOG.error(">> Excel file Download error", e);
return ResponseWrapper.failWithMessage(messageSource.getMessage("fail_code", null, Locale.ENGLISH));
}
}

AJAX open does not accept Servlet

I am currently making a small program using AJAX. I want to send a JSON String to a Servlet, but it doesn't work. In my browser I get the error "Uncaught TypeError: Cannot read property 'open' of undefined"
I'm guessing that this means, that it can't find the Servlet in the following line:
xmlHttp.open("POST", "../JSONServlet", true);
However, I have made similar programs before and never had this problem, so I don't know what to do to make it work.
My html and js files are in Web Pages/ex06 and my Servlet is in Source Packages/servlets/JSONServlet, however I've tried moving it somewhere else (even though I have made programs that worked like this), but it didn't help.
This is the html and javascript:
var xmlHttp;
window.onload = initAjax();
function initAjax() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE6 or older
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (ex) { // noch ältere MS Produkte
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (ex) {
}
}
}
}
function doJSON1() {
var car = new Car("Mercedes", "SLK", 2012); // car erstellen
var carAsJSON = JSON.stringify(car); // json-String machen
alert("Car object as JSON:\n " + carAsJSON);
xmlHttp.open("POST", "../JSONServlet", true); // here is the problem
xmlHttp.onreadystatechange = handleObjectRequest;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(carAsJSON); // json-String senden
}
function handleObjectRequest() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
jsontext = xmlHttp.responseText;
alert(jsontext);
var benz = JSON.parse(jsontext);
var output = benz.brand + " " + benz.model;
document.getElementById("serverResponse").innerHTML = output;
}else{
alert("nope");
}
}else{
alert("...");
}
alert("state change");
}
function Car(brand, model, year, color) {
this.brand = brand;
this.model = model;
this.year = year;
this.color = color;
}
<input type="button" value="JSON-Object senden&empfangen" onclick="doJSON1();"/>
This is the method in my Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStreamReader isr = new InputStreamReader(request.getInputStream());
try {
Gson gson = new Gson();
// auto aus request erstellen
Car car = gson.fromJson(isr, Car.class);
// anderes auto schreiben
Car car2 = new Car("audi", "tt", 2014);
gson.toJson(car2, out);
} catch (JsonSyntaxException e) {
Gson gson = new Gson();
String[] winter = gson.fromJson(isr, String[].class);
String[] summer = {"Jun", "Jul", "Aug"};
out.println(gson.toJson(summer));
}
out.flush();
out.close();
}
My Car class is a simple data class with getters and setters, a default constructor, a custom constructor, and a toString.
You need to have an instance of the XMLHttpRequest() to use the open() method, so add the following line of code:
var xmlHttp = new XMLHttpRequest();
Before you use the open() method like so:
xmlHttp.open("POST", "../JSONServlet", true);
EDIT: - You also have a typo as pointed out by #james before i did, in you're initAjax function you have a variable xmlhttp were as you're global variable is xmlHttp , both are not the same.

Getting a json object from HttpServletResponse

I am sending a json object via ajax call.
When I try to print the json's values I am getting nulls.
What am I doing wrong?
Servlet:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{\"PARENT\":\"2\",\"VAL\":\"X7280\"},{\"PARENT\":\"2\",\"VAL\":\"X8338\"}]");
}
javascript:
function handleIt() {
var url = "myservlet";
var parameters = "method=method";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
var ddl3 = http.responseText;
for(var key in ddl3){
var id = ddl3[key].PARENT;
var lbl = ddl3[key].VAL;
alert (lbl);
}
}
}
http.send(parameters);
}

error ajax and Jena

When I try to call Jena using AJAX in my servlet I get this error:
java.lang.ClassNotFoundException: com.hp.hpl.jena.sparql.core.Prologue
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
at fr.objective.blogomatic.semantic.web.ServletAjax.doGet(ServletAjax.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
This is my Jena code:
class classUsingJena {
public void execute(){
String queryString = PREFIXES
+ " Select ?label "
+ " where {"
+ " ?description j.5:entity-label ?label ." + " } ";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out,results, query);
qe.close();}
}
It's running fine, but when I call this function using servlet I get the error described previously.
This is my servlet code:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String service = req.getParameter("service");
classUsingJena jena= new classUsingJena() //bug
return;}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
#Override
public void init() throws ServletException {
ServletConfig config = getServletConfig();
urlAjax = config.getInitParameter("urlAjax");
}
My java script code that runs fine:
$("#Analyser").click(function(){
var article = $("#TxtArea").val();
ajaxFunction("acteur",article);
console.log(article);
});
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(valeur,txt) {
if(xmlhttp) {
xmlhttp.open("GET","ajax?service=ajax&valeur="+valeur+"&text="+txt,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
$("#J").text("");
parseXml(xmlhttp.responseXML);
}
else {
//alert("Error during AJAX call. Please try again");
}
}
}
function parseXml(xml)
{
$(xml).find("nom").each(function()
{
$("#J").append($(this).text() + "<br />");
});
}
In the pom I had declared the old version of Arq 1.8.7 instead of 2.8.7. Now it's running fine.

Newbie AJAX Qn: request.send(information)

I am completely new to AJAX hence this question. I want to send some information from my javascript code to my servlet.
function getDetails() {
vals = document.getElementById("name").value;//works: vals does get inputted value
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "ValidateUser.do";
request.open("POST", url, true);
request.onreadystatechange = displayDetails;
//How do I send the value of "vals" to my servlet?
request.send("name="+vals);
}
When I run req.getParameter("name") on my servlet, I always get no value even though "vals" does contain the inputted value. So my question is- how do I access this value from my servlet?
EDIT:
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
return request;
}
FURTHER EDIT:
Servlet code: I want the println statement to print out the name.
//shortened: this method is called by a ControllerServlet
public Object perform(HttpServletRequest req, HttpServletResponse resp) {
//retrieve customer from database
model = SeekerCustomer.getCustomer(req.getParameter("name"));
System.out.println(req.getParameter("name"));
}
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
function postReq(){
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("my_Result_tag").innerHTML=mypostrequest.responseText //this is where the results will be put!
}
else{
alert("An error has occured making the request")
}
}
}
var vals = document.getElementById("name").value
var parameters="name="+vals
mypostrequest.open("POST", "ValidateUser.do", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
}
In the servlet access vals using:
request.getParameter("name");

Categories

Resources