JSP not receiving AJAX response from Servlet - javascript

I have a simple jsp page that sends an ajax request to a servlet and awaits a response. Unfortunately, it's not receiving the response after many attempts. The ajax requests are being transmitted but response isn't being received.
As of now, I have a dropdown in my page and a textbox. I am trying to get the value selected in the dropdown to be printed in the textbox on the dropdown's "onchange" event.
Here's my code. Any help regarding this would be very welcome.
JSP PAGE
<script>
function ajaxrequest(){ return new XMLHttpRequest();}
function ac()
{
var myajaxrequest = new ajaxrequest();
if(myajaxrequest==null){alert("AJAX NOT WORKING");}
else
{
alert("AJAX WORKING");
var ind2=document.getElementById("dd1").value;
myajaxrequest.onreadystatechange=connection;
myajaxrequest.open("GET", "../ajaxservlet?dd1="+ind2,true );
myajaxrequest.send(null);
}
}
function connection()
{
if(myajaxrequest.readyState==4)
{
var x=myajaxrequest.responseText;
document.getElementById("result").innerHTML = x;
}
}
</script>
<body>
<form id = "form1" name ="form1" >
<select id="dd1" name="dd1" onchange= "ac()">
<option>Please select </option>
<option>ankur</option>
<option>akshay</option>
</select>
<input type="text" id="result" name="result" />
</form>
</body>
SERVLET :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("hitting servlet");
String abc = request.getParameter("dd1");
System.out.println(abc);
PrintWriter pw=response.getWriter();
response.setContentType("text/html");
pw.println(abc);
}
The values selected in the dropdown are getting printed in the console but aren't being transmitted back.
Thanks for your time.

myajaxrequest is local to the ac() function since you've used the var keyword. You cannot access it in the connection() function.
Try declaring your connection() function within ac() itself.
Instead of checking the status of readyState, using XHR level 2, you can simply attach a handler to the onload event.
BTW, if native XHR isn't supported ajaxrequest() will throw an error; it won't return null.

Try initializing myajaxrequest globally.

Related

Getting data from a servlet to JSP and sending that data again to another servlet through ajax

I am new to JSP and servlet. I am designing a library management system in tomcat version 10.0, in that when user sign-in using his userid and password in html form it will send it to login servlet once credentials matched using RequestDispatcher it sent userid to userlogin(home) JSP for further use.
Until this everything is working and in that JSP there is two actions, one is the user can check for book availability in MySQL Database and his/her book's return date, if he/she borrowed any book otherwise no books borrowed message will shown.
The task is, I want to get the above two actions' result through ajax. Once the user enters the book name to be searched in input field and button is pressed the ajax should call the servlet and get the value corresponding to it from database and create data in htmltable format and return it to ajax call and ajax on getting it, should display it in a particular div using innerhtml or DOM html function. The same method is user for getting the returndate of the book user borrowed.
Problem:
But once the book name entered in field and button is pressed the action is called but it shows a 405 error that the servlet doesnot allow GET method, eventhough in ajax call and my servlet I used POST method. I noticed a thing that when user sign-in, the URL bar shows login servlet URL eventhough the page shows JSP page and also once the ajax is called the data is send from login servlet(http://localhost:8080/library/UserLogin) and also received in the same login servlet(http://localhost:8080/library/UserLogin?search=java) which seems to working in get method (but I used POST on both sides though), so I guess the data is still moving in the same servlet URL.
UserLogin.java
public class UserLogin extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
//getting userid and password for checking with database//
String userid=request.getParameter("uid");
String pass=request.getParameter("pwd");
try{
Connection connect=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password");
PreparedStatement ps =connect.prepareStatement("select * from library.user where userid = ? and pass = ?");
ps.setString(1, userid);
ps.setString(2, pass);
ResultSet rs=ps.executeQuery();
if(rs.next()){
request.setAttribute("userid",userid);
RequestDispatcher rd=request.getRequestDispatcher("userlogin.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("http://localhost:4200/user");
rd.forward(request,response);
}
}catch(SQLException e){
System.out.println(e);
}
}}
'
userlogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
<link rel="stylesheet" href="css/app.css">
<link rel="icon" href="images/logo.jpg" type ="image/x-icon">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="heading">
<div class="title">
<h1>Online Library</h1>
</div>
<div class="logo">
<i class="fas fa-book-reader fa-7x"></i>
</div>
</div>
<div class="search-container">
<form>
<input type="text" name="search" id="search" placeholder="Search by book genre (Eg:Search Java for Java books)" />
<button id="getbook"><i class="fas fa-search"></i></button>
<!--the button for ajax to get book availability table-->
</form>
</div>
<hr>
</div>
<button id="mybook">My Books and Due date</button>
<!--the button for ajax to get user's book returndate table-->
<%String suserid=(String)request.getAttribute("userid");
out.println("name:"+suserid);%> <!--storing userid for using it for user's book returndate-->
<div id="books"> <!--div tag where the table will show-->
</div>
<script>
$(document).ready(function(){
$("#getbook").click(function(){
var search=$("#search").val()
$.ajax({
type:'POST',
url:'Issuedbooks',
data:search,
success:function(response){
console.log(response);
$("#books").html(response);
},error:function(request,status,error){
alert("Error:"+error+status);
}
});
});
$("#mybook").click(function(){
var userid= suserid; /*I also doubt on this declaration if it is wrong give suggestion please*/
$.ajax({
type:'POST',
url:'mybooks',
data:userid,
success:function(response){
console.log(response);
$("#books").html(response);
},error:function(request,status,error){
alert("Error:"+error+status);
}
});
});
});
</script>
</body>
</html>
Issuedbooks.java
public class Issuedbooks extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<html><body>"); //creating a html table//
String genre=request.getParameter("search"); //the value in input field of jsp page//
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select * from library.issue where genre='"+genre+"'");
out.println("<table border=1>");
out.println("<tr><th>Bookid</th><th>Returndate</th><th>Bookname</th><th>Authorname</th></tr>"); //creating table header//
while(rs.next()){
String bookid=rs.getString(3);
String returndate=rs.getString(5);
out.println("<tr><td>"+bookid+"</td><td>"+returndate+"</td>");
}
Connection con1=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password"); //as I have to get data from two database I have created two connections//
Statement stmt1 = con1.createStatement();
ResultSet rs1=stmt1.executeQuery("select * from library.books where genre='"+genre+"'");
while(rs1.next()){
String bookname=rs1.getString(2);
String authorname=rs1.getString(3);
out.println("<td>"+bookname+"</td><td>"+authorname+"</td></tr>"); //continuing to add this in same table//
}
out.println("</table");
out.println("</body></html>"); //end of htmltable//
}catch(SQLException e){
e.printStackTrace();
}
}}
mybooks.java
public class mybooks extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<html><body>");
String userid=request.getParameter("suserid"); //getting userid from jsp which is obtained from userlogin servlet//
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select * from library.issue where userid='"+userid+"'");
out.println("<table border=1>");
out.println("<tr><th>Bookid</th><th>IssueId</th><th>Userid</th><th>Bookid</th><th>Issuedate</th><th>Returndate</th><th>Genre</th></tr>");
if(rs.next()){
String issueid=rs.getString(1);
String userid=rs.getString(2);
String bookid=rs.getString(3);
String issuedate=rs.getString(4);
String returndate=rs.getString(5);
String genre=rs.getString(7);
out.println("<tr><td>"+issueid+"</td><td>"+userid+"</td><td>"+bookid+"</td><td>"+issuedate+"</td><td>"+returndate+"</td><td>"+genre+"</td></tr>");
}else{
out.println("No books issued");
}
}catch(SQLException e){
e.printStackTrace();
}
}}
So these are my code and on running these I get error like this.
HTTP GET is not supported by this url in my tomcat server. I did everything using POST method since I am getting error for using GET method and the url in jsp page still displays the userlogin servlet URL and the data isn't get passed this URL on calling ajax. I have checked with web.xml everything is fine.
Sorry for lengthy description, I just want to clearly describe my problem to get answers. Thanks in advance :)
Sorry for sharing the code again but I didn't figure out where I am missing the part. Here I have only shared the part that isn't working
userlogin.jsp
<%String userid=(String)request.getAttribute("userid");%> //converted to received object to string here//
<input type="hidden" id="userid" value='<%out.println(userid);%>'> //set value of input as userid and hide it so I can use it for ajax//
<input type="button" id="mybook" value="My books and due date" />
<div id="books">
</div>
<script>
$("#mybook").click(function(){
console.log("test print");
var userid= $("#userid").val();
$.ajax({
type:'POST',
url:'mybooks',
data:{user_id:userid.toString()}, //I have a doubt whether it is changed to string or not so again tried to transfer it as string//
success:function(response){
console.log(response);
$("#books").html(response);
},error:function(request,status,error){
alert("Error:"+error+status);
}
});
});
</script>
mybooks.java
public class mybooks extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<html><body>");
String userid=request.getParameter("user_id");
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","password");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select * from library.issue where userid='"+userid+"'");
out.println("<table border=1>");
out.println("<tr><th>Bookid</th><th>IssueId</th><th>Userid</th><th>Bookid</th><th>Issuedate</th><th>Returndate</th><th>Genre</th></tr>"); //i am getting upto this content in response//
while(rs.next()){
String issueid=rs.getString(1);
String uid=rs.getString(2);
String bookid=rs.getString(3);
String issuedate=rs.getString(4);
String returndate=rs.getString(5);
String genre=rs.getString(7);
out.println( "<tr><td>"+issueid+"</td><td>"+uid+"</td><td>"+bookid+"</td><td>"+issuedate+"</td><td>"+returndate+"</td><td>"+genre+"</td></tr>"); //I didn't get this part in response, I doubt whether the data is receiving in servlet evethough it is passed here//
}out.println("</table>");
out.println("</body></html>");
}catch(SQLException e){
e.printStackTrace();
}
}}

how do i show windows.alert("msg") after send a response to jsp from servlet?

A user sends a request to servlet, and the servlet sends a response back to jsp,
i also want to show alert("message") on jsp after the servlet response to jsp,
how should i do? please help me, thank you.
<FORM method="post" action="/test/Application.do">
<input type="submit" value="cancel" onclick="return confirm('sure?')"/>
<input type="hidden" name="action" value="cancelApp"/>
</FORM>
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html; charset=UTF-8");
String action = req.getParameter("action");
if (action.equals("cancelApp")) {
//to something with database
String url = "/front-end/Application_Topping_MainPage.jsp";
RequestDispatcher dispatcher = req.getRequestDispatcher(url);
dispatcher.forward(req, res);
return;
}
According to your code, if the page 'front-end/Application_Topping_MainPage.jsp' is only visible as a result of this action, just add below code snippet in the jsp file.
<script>
window.onload = function(){alert('message')}
</script>
if this page maybe visited by other manner other than post the form, and you only want the alert show after post, you can add such code in your jsp file.
<% if (flag) { %>
<script>
window.onload = function(){alert('message')}
</script>
<% } %>
And in your doPost set that flag to be true accordingly.

Run multiple ajax when page load

I write three ajax function like below:
function showClass()
{
...
var url="getObjectProperty?"
....
}
function showDtPro()
{
...
var url="getDataTypeProperty?"
....
}
function showObjPro()
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your Browser Don't support AJAX");
return;
}
var url="getObjectProperty?";
url=url+"sid="+Math.random();
xmlHttp.onreadystatechange=loadObjPro;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
except the "url" is different, the other things are the same.This ajax is used to get the data from three different servlets and update the tag in html.
One of the servlets is below:
//This function is used to get the data from an jena model and response the data to the client.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
//
ArrayList<String> ObjectPropertyNames=new ArrayList<String>();
//Define the jenaOwlModel
JenaOWLModel jenaOwlModel;
try {
OntModel ontmodel=MyModelFactory.getJenaModel().getOntModel();
ExtendedIterator ObjectProperties = ontmodel.listObjectProperties();
while(ObjectProperties.hasNext()){
ObjectProperty property = (ObjectProperty) ObjectProperties.next();
if(property.getLocalName()!=null)
{
ObjectPropertyNames.add(property.getLocalName());
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String AllObjectProperties="";
for(int i=0;i<ObjectPropertyNames.size();i++)
{ AllObjectProperties=AllObjectProperties+ObjectPropertyNames.get(i)+"#";
}
System.out.print(AllObjectProperties);
out.print(AllObjectProperties);
out.flush();
out.close();
}
The other servlet is almost the same with this one.Now I want to load the data from the three servlets when the page is loaded.So I write in the windows.onload function like below:
window.onload=function()
{
showClass();
showObjPro();
showDtPro();
}
But it doesn't run as expect.Sometimes,only the last functionshowDtPro();fetch the data.The other two function don't fetch the data. Sometimes, the tag should be updated by showClass() and showObjPro() appear the data get from showDtPro().
<div id="class">
<h4>Class</h4>
<ul id="rdfclass" type="dclass"></ul>
</div>
<div id="obj">
<h4>Object Property</h4>
<ul id="rdfobjpro" type="dobjpro"></ul>
</div>
<div id="dt">
<h4>Datatype Property</h4>
<ul id="rdfdtpro" type="dtpro"></ul>
</div>
the html tag is above. Correspondingly, the three functions are used to update the three<ul>tag.
I am a beginner to web develop. I hope to get your help! Thank you !
That is because ajax is asynchronous. You'll have to implement some callbacks etc..
The execution is not synchronous in case of ajax.

Post parameters from AJAX request undefined in form scope in ColdFusion

I am working on a ColdFusion 8 training application where I'm making some AJAX requests (without any libraries such as jQuery) to support a very basic CRUD application.
The high level architecture includes a CFM view, a CFC with remote access methods which receive the AJAX requests, and a CFC which acts as a model and has all of the database queries.
For just retrieving data that doesn't require any sort of bind variables (like getting all rows from the table), the AJAX queries are working fine. When I try to post anything to the CFC middle layer, however, I'm getting errors about the values I'm looking for being undefined in the Form scope (which from my understanding is where post parameters will be stored). I even dissected the requests with Tamper Data and verified that the names and values of the post parameters are as I expect them to be.
Here is an example of the JS AJAX requests:
function addLocation(locToAdd) {
var thisAccess = new AccessStruct("POST", "jsontest.cfc?method=addNewLocation", getLocations, "newLoc=" + JSON.stringify(locToAdd));
accessWrapper("addLoc", thisAccess);
function accessWrapper(action, accessDef) {
var ajaxRequest = new XMLHttpRequest();
var nextStep;
if (action != "getLocs") {
nextStep = getLocations;
} else {
nextStep = buildTable;
}
ajaxRequest.onreadystatechange = function() { // using a closure so that the callback can
if (ajaxRequest.readyState == 4) { // examine the request and nextStep
if (ajaxRequest.status == 200) {
if (nextStep != null) {
nextStep(ajaxRequest);
}
return true;
} else {
alert("Request Could Not Be Completed; Errors On Page");
return false;
}
}
}
ajaxRequest.open(accessDef.method, accessDef.url, true);
ajaxRequest.send("newLoc=" + accessDef.params);
}
function Loc(locCode, parLocCode, name, addrL1, addrL2,
city, stateProv, postal, locTypeCode) {
this.locCode = locCode;
this.parLocCode = parLocCode;
this.name = name;
this.addrL1 = addrL1;
this.addrL2 = addrL2;
this.city = city;
this.stateProv = stateProv;
this.postal = postal;
this.locTypeCode = locTypeCode;
}
function AccessStruct(method, url, nextStep, params) {
this.method = method;
this.url = url;
this.nextStep = nextStep;
this.params = params;
}
Essentially what's happening on the page is that a table populated by all the location (loc) records is being rendered for a "user". There is a form to add a new user, and when they click the add button, a Loc structure is created containing the information they entered and is passed to the addLocation function. This creates an Access structure, which will include the request URL, method, the name of a function to act as a callback, and any post parameters. This is all passed into the accessWrapper function, which will create the XMLHttpRequest and process the AJAX request. I used a closure for the onreadystatechange callback function so that it could be aware of the XMLHttpRequest object and the callback function defined in the Access structure (this callback function will be generally be used to refresh the view table after a record is added, deleted, or edited).
Here is the cffunction within the middle-layer CFC where the problem is being reported from. I won't bother to post the DAO CFC as that has been tested elsewhere and is not even being reached during this process (because it's failing at the middle [or controller] level)
<cffunction name="addNewLocation" output="false" access="remote">
<cfset var deserializedLocation = "">
<cfscript>
deserializedLocation = DeserializeJSON(Form.newLoc);
</cfscript>
<cfobject component="locationDAO" name="locationDAOObj">
<cfinvoke
component="#locationDAOObj#"
method="addLocation">
<cfinvokeargument name="code" value="#deserializedLocation.locCode#">
<cfinvokeargument name="parentCode" value="#deserializedLocation.parLocCode#">
<cfinvokeargument name="name" value="#deserializedLocation.name#">
<cfinvokeargument name="addr1" value="#deserializedLocation.addrL1#">
<cfinvokeargument name="addr2" value="#deserializedLocation.addrL2#">
<cfinvokeargument name="city" value="#deserializedLocation.city#">
<cfinvokeargument name="stateProv" value="#deserializedLocation.stateProv#">
<cfinvokeargument name="postal" value="#deserializedLocation.postal#">
<cfinvokeargument name="locationType" value="#deserializedLocation.locTypeCode#">
</cfinvoke>
</cffunction>
The error in the request response is:
500 Element NEWLOC is undefined in FORM
Like I said before, I've checked the request in Tamper Data, and it looks fine there. Thanks in advance for any help you great folks might be able to offer!
There absolutely is a FORM scope when you do an Ajax post to a CFC.
This example POSTs form data via Ajax to a CFC function with no arguments and returns the JSON format of the FORM scope. Yes, you should have arguments to document, specify required/not required and data type, but they're not mandatory.
Is there any reason you aren't using jQuery? It would probably make your life much easier.
There must be something wrong with how you're sending the form data to the Ajax call. If you use FireBug to watch your Ajax calls, you can see the POSTed parameters.
HTML
<html>
<head>
<title>Ajax POST to CFC</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="test.js">
</head>
<body>
<form id="foo" action="" method="post">
<input type="text" id="a" name="a" value="Hello" />
<br />
<input type="text" id="b" name="b" value="Goodbye" />
<br />
<textarea id="data" cols="30" rows="10" disabled="true"></textarea>
<br />
<input type="button" id="btnSubmit" value="Do Ajax!" />
</form>
</body>
</html>
JavaScript
$(document).ready(function() {
$('#btnSubmit').on('click', function() {
$.ajax({
asynch : true,
type : 'POST',
dataType : 'json',
url : 'test.cfc?method=testing&returnformat=json',
data : {
a : $('#a').val(),
b : $('#b').val()
},
success : function(data, textStatus) {
$('#data').val(JSON.stringify(data));
}
});
});
});
CFC
<cfcomponent>
<cffunction name="testing" access="remote" output="false" returntype="string">
<cfreturn serializeJSON( form ) />
</cffunction>>
</cfcomponent>
Old School, no jQuery, just plain ol' JavaScript
I found a simple example of an Ajax POST without jQuery here:
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
HTML
Remove the jQuery SCRIPT tag, change the other SCRIPT to test-nojq.js and change the submit button to add an onclick event.
<input type="button" id="btnSubmit" value="Do Ajax!" onclick="doSubmit();" />
JavaScript: test-nojq.js
function doSubmit(){
var http = new XMLHttpRequest();
var url = "test.cfc";
var params = "method=testing&returnformat=json";
params += "&a=" + document.getElementById('a').value;
params += "&b=" + document.getElementById('b').value;
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("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
document.getElementById('data').value = http.responseText;
}
}
http.send(params);
}
Make newLoc into an argument and it should work.
<cffunction name="addNewLocation" output="false" access="remote">
<cfargument name="newLoc">
...
</cffunction>
update: not sure why I encountered no form scope one time calling a remote method. Anyway, it isn't true but the rest of the answer should still hold true.

sending long strings in jquery post

I am not able to send long strings (more than 96 char. Tested in FF12 and Chrome 18) in jquery post method.
My servlet is -
public class TestServletAsh extends HttpServlet{
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doPost(req, resp);
String xml=req.getParameter("xml");
}
}
and my jquery post request is -
<body>
<script>
function callMe() {
var str = "dkghjkdf dfg jdfgjd gkdfgdjk gdf gdfg dkjgdfjk gdjgdfjg dfjkgdfjkg dfjkgdfjkg dfjkgdf jkdfgdjhgs";
$.post(
"TestServletAsh",
{ xml:str },
function(data) {
alert("mission successfull"); //nothing to do with it or data here in this SO question
}
);
}
</script>
Click to send request
</body>
I am debugging the servlet and I find "xml=null". I am using jboss as a webserver.
Can anyone please tell me where is the problem.
When I use another version of jquery.post like this -
$.post(
"TestServletAsh?xml="+str,
function(data) {
alert("mission successfull"); //nothing to do with it or data here in this SO question
}
);
Then I am able to send around 6000 characters. For more than 6000 characters Firebug says - "405 Aborted". Why ?? Any idea ?
May be your webserver i.e. Jboss could be the issue.
You can look into changing server config parameters
Try setting maxPostSize = 0 in conf/server.xml file

Categories