Run multiple ajax when page load - javascript

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.

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();
}
}}

Passing value from java to Javascript

I'm making an Android app using webview.
The app can print out receipts. What I want to do is when the printer is not working, alert box shows up to tell the printer isn't working, and return false to the form's onsubmit event to prevent form from being submitted.
Java code:
public class JSKicker {
#JavascriptInterface
public void callPrint(final String argumet) {
Thread thread = new Thread(new Runnable() {
public void run() {
int nRtn;
connectionNum = myPrinter.Connect("000.000.0.000");
if(connectionNum < 0){ //Printer not working
webview.post(new Runnable() {
#Override
public void run() {
String script = "alert('Printer Error'); return printer_connection = false;";
webview.evaluateJavascript(script, new ValueCallback<String>() {
#Override
// I can't figure out what to do here...
});
}
});
}else{ //Printer is working properly
connectionNum = myPrinter.SetLocale(8);
strText = argument;
nRtn = myPrinter.PrintText(strText, "SJIS");
nRtn = myPrinter.PaperFeed(64);
nRtn = myPrinter.CutPaper(1);
myPrinter.Disconnect();
}
}
});
thread.start();
}
JavaScript in header:
<script type="text/javascript">
function gate(){
jQuery.ajax({
url:'/cart_info.php',
type:'GET'
})
.done( (data) => {
window.JSKicker.callPrint(data);
})
if (printer_connection = false) {
return false;
}else{
return true;
}
}
</script>
HTML form tag:
<form method="post" id="order_form" onsubmit="return gate();">
How can I get this work?
Could you do it thru WebView.evaluateJavascript()?
https://developer.android.com/reference/android/webkit/WebView.html#evaluateJavascript(java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.String%3E)
So with that you could send simple CustomEvent to document in WebView
webView.evaluateJavascript("document.dispatchEvent(new Event('printer_error', { details: "No printer found!" }));");
and in JavaScript you can hook listener for your custom event to react.
document.addEventListener('printer_error', e => alert(e.details));
Didn't test this so might be that at least evaluateJavascript() needs callback function.
WebSocket can solve your problem.
WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time. The client establishes a WebSocket connection through a process known as the WebSocket handshake.
Its very straight forward and easy to implement.
You can follow referrer links for more details:-
JAVA WebSocket:- WebSocket using Spring Boot, WebSocket using Simple JEE
Browser WebSocket(JavaScript):- WebSocket API
In Android ,if you want webview pass value to JavaScript.
First,you need to set the webview enable the JavaScript,
private WebView mWebView;
void onCreate(){
mWebView = findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
}
And ,in you want do some thing code
if(connectionNum < 0){ //Printer not working
// I need to do something here to send a message that the printer isn't working to JS.
//In thread can not use mWebView,should send message to MainThread to do
// mWebView.loadUrl("javascript:javaCall()");
Message msg = new Message();
msg.what = 1;
myHandler.sendMessage(msg);
//myHandler can be your MainThread send to here
}
And where the mWebView created in your code, be in main thread ,you can use the
Handler to deal with the message sended to here.
private Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// this 1 is just thread send to here
if (msg.what == 1) {
//and here can do the webview UI method
mWebView.loadUrl("javascript:javaCall()");
}
}
};
the javaCall() is where you JacaScript invoke method,in javaScript you can writre like this:
<script language="javascript">
function javaCall(){
alert("Printer Error");
//other thing you can do
}
</script>
if you have problem ,you can refer to the official document.
public void loadUrl (String url)
Loads the given URL.
Also see compatibility note on evaluateJavascript(String, ValueCallback).
webview use link

How to set JS effects on progress bar managed by a backing bean?

I have
<h:form id="form">
<p:progressBar id="pbAjax" value="#{backingBean.value}" labelTemplate="{value} %"/>
<p:poll listener="#{backingBean.updateValue()}" update="pbAjax"/>
</h:form>
And
#ManagedBean
public class BackingBean implements Serializable {
private Integer value;
#PostConstruct
public void init(){
this.value = (int)Math.round(Math.random()*10);
}
public Integer getValue(){
this.value = (int)Math.round(Math.random()*10);
return value;
}
public void setValue(Integer value){
this.value = value;
}
public void updateValue(){
this.value = (int)Math.round(Math.random()*5);
}
}
The progress bar is working fine.
Now I would like to implement a "ease-in" effect.
Since the values change with Ajax requests on a backing bean and not a Javascript function, how can I put a javascript effect on the progress bar, or "intercept" the XHR response to apply a "ease-in" effect in Javascript before it updates the component?
If it can help, I see this kind of Ajax response :
<?xml version='1.0' encoding='UTF-8'?>
<partial-response id="j_id1">
<changes>
<update id="form:j_idt40:18:pbAjax">
<![CDATA[
<div id="form:j_idt40:18:pbAjax" class="ui-progressbar ui-widget ui-widget-content ui-corner-all">
<div class="ui-progressbar-value ui-widget-header ui-corner-all" style="display:block;width:9%">
</div>
<div class="ui-progressbar-label" style="display:block">
9 %
</div>
</div>
<script id="form:j_idt40:18:pbAjax_s" type="text/javascript">
$(function() PrimeFaces.cw(
"ProgressBar",
"widget_form_j_idt40_18_pbAjax",
{
id:"form:j_idt40:18:pbAjax",
initialValue:6,
ajax:false,
labelTemplate:"{value} %"
}
);
});
</script>
]]>
</update>
<update id="j_id1:javax.faces.ViewState:0">
<![CDATA[-1946172786751610988:-1619424769397867671]]>
</update>
</changes>
</partial-response>
Thanks for any help.
With the setup shown above, the following solution works.
I've set the "update" method to static in my Managed Bean.
public static Integer updateValue(){
return (int)Math.round(Math.random()*5);
}
Created a servlet with the content of my static method in the response body.
#WebServlet(name = "ProgressBarServlet", urlPatterns = ("/ProgressBarServlet"})
public class ProgressBarServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("ProgressBarUpdate", "no-cache");
PrintWriter out = response.getWriter();
out.print(BackingBean.updateValue()+"");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
Created a cyclic XHR request on the servlet url.
<script type="text/javascript">
setInterval(function () {
testAjax("ProgressBarServlet");
}, 5000);
function testAjax(servletURL) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", servletURL, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
PF('pbAjax').setValue(xmlhttp.responseText);
}
else {
PF('pbAjax').setValue("Error");
}
}
};
xmlhttp.send(null);
}
</script>
So the value of the progress bar is set with PrimeFaces Javascript and has the ease-in effect.
Albeit it might not be the most efficient way to update components, this solution can be useful for one or few components.
It is not relevant in my case, because I have a p:dataTable with a progress bar in each row and cannot link generated ids to Javascript.

JSP not receiving AJAX response from Servlet

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.

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