Show java servlet process in web - javascript

I'm developing a small web app that queries a few databases to do data predictions, then returns an object with the predicted result.
That's somewhat working already, but data processing in the servlet can go over half an hour depending on query filters, I usually set up a javascript "loading" div on submit, but its a bit sad.
So the question is, can I somehow send messages to the web client while the servlet is processing so it doesn't look like the page died? (improving the loading div with actual info on how the process is going)

Just add the preloader before sending the request and remove that preloader on success.
var isBool = false;
function communicateWithServer(){
$("#preloader").show();
var isBool = false;
$.ajax({
url : 'url',
data : {
},
type : 'POST',
dataType : 'text',
success : function(response) {
isBool=true;
$("#preloader").hide();
//Show success
},
error : function(request, textStatus, errorThrown) {
$("#preloader").hide();
//show error
}
});
secondComm();
}
function secondComm(){
$.ajax({
url : 'url2',//send the response from your second servlet to this
data : {
},
type : 'POST',
dataType : 'text',
success : function(response) {
$("#preloader").text(response.value);
if(!isBool){secondComm();}
//
},
error : function(request, textStatus, errorThrown) {
if(!isBool){secondComm();}
//show error
}
});
}
Please do not get confused with the jquery you can do this without jquery too.
function communicateWithServer() {
document.getElementById("preloader").style.display = 'block';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//show success
} else {
//show error
}
document.getElementById("preloader").style.display = 'none';
};
xhttp.open("GET", url, true);
xhttp.send();
}

Related

how to compare response from jsp page to ajax page?

i am comparing the response i got from jsp page to ajax . i want to perform if out.print() print success message so i want to perform action in success ajax function . i am comparing data . but it is not working . i always go to else section . i am new in ajax . can please help me out with this problem.
$.ajax({
url: "login.jsp",
//datatype: "text",
type: "POST",
data: datatopost,
success: function(data){
if(data.search("success")!=-1){
console.log(data.data);
$('#loginmessage').html(data);
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
// window.location = "mainpageloggedin.jsp";
//$('#loginmessage').text(data);
}else{
// $('#loginmessage').text(data);
//hide spinner
//window.location = "mainpageloggedin.jsp";
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
}
},
error: function(){
$("#loginmessage").html("<div class='alert alert-danger'>There was an error with the Ajax
Call. Please try again later.</div>");
//hide spinner
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
}
});
jsp code...
<%# include file="connection.jsp"%>
<%
String email=request.getParameter("loginemail");
String loginpass=request.getParameter("loginpassword");
ResultSet rs=st.executeQuery("select password from users where email='"+email+"'");
if(rs.next())
{
String password1=rs.getString(1);
if(password1.equals(loginpass))
{
session.setAttribute("email",email);
out.print("success");
}
else
{
out.print("invalid combination of email and password");
}
} else
{out.print("this account does not have information");
}
%>
I suspect it's related to the .search() or the type of data that is being returned.
First, always review console and network to see what data package is being sent and received for AJAX. If you're not getting what's expected back, you may need to look at your Java.
If you're getting whats expected, consider the following code.
$.ajax({
url: "login.jsp",
datatype: "text html",
type: "POST",
data: datatopost,
success: function(data){
console.log(data);
if(data.search("success") > -1){
console.log("Found 'success' in AJAX Package.");
$('#loginmessage').html(data);
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
} else {
$("#spinner").css("display", "none");
//show message
$('#loginmessage').html("Login Failed. " + data);
$("#loginmessage").slideDown();
}
},
error: function(x, stat, err){
$("#loginmessage").html("<div class='alert alert-danger'>There was an error with the Ajax. Please try again later. (" + stat +", " + err + ")</div>");
//hide spinner
$("#spinner").css("display", "none");
//show message
$("#loginmessage").slideDown();
}
});
In most cases, the AJAX will not error unless there is an error with the Web Server, so a 401, 404, or 500 error. So we want to make sure we're doing most of the work in in success, which is triggered when we get a 200 status.
So some text package is coming back. Based on your Java, this could be success, invalid combination of email and password, or this account does not have information. We can see what that package is upfront with console now. We then need to test it.
Since this is for AJAX, there is no way to test it for me. It's often best to use the simplest logical test. So != -1will work, yet > -1 is just as good and less confusing.
Can you try something like this
function crudPost(e) {
e.preventDefault();
let name = document.querySelector('#name').value;
let email = document.querySelector('#email').value;
let parameters = "name=" + name + "&email=" + email;
let xhr = new XMLHttpRequest();
xhr.open('POST', 'process.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.onload = function () {
if (this.status == 200) {
console.log(this.responseText)//get response from ur jsp
// do stuff
}
let parameters = "name=" + name + "&email=" + email; //pass values when send
}
xhr.send(parameters)
form.reset();
}
I just dont understand the problem u r facing in the code but try in this format it might help

I've a not working AJAX function

I'm building a time management system for the place I work for. While coding it I've created a system which the user can configure the database details (like the wordpress first run install) and once the data is saved successfully I want to show the next step.
The first part is working perfectly but I've run into some issues with the second part where the system checks the connection and start creating the database and the needed tables.
Up to now I've been using JSON to send and receive PHP response text. But now I wanted to create a AJAX function to the same as JSON. But the problem is the AJAX function is sending the data but I can't get the response text.
I went through most of the SO titles came up when I did a google search (might have missed once) but none of them worked. When I try to get the output from an alert it shows as oject[Object] on the popup.
Below is my jquery which I have the AJAX coded into.
function checkResponse(){
var res = $('#response').text();
if(res === "Saved"){
$.ajax({
url: './bin/config/createConfig.php',
type:'get',
data:{check:'check'},
dataType:'json',
complete: function (data) {
alert(data.responseText);
}
});
// $('#nextstep').show();
// $('#dbConfig-details').hide();
}
}
Above function is called by the below setTimeOut.
if(noEmpty && confirm('Are you sure all details to be true?')){
createConfig();
setTimeout('checkResponse();', 1000);
}
This is the PHP which the above AJAX send data to.
if (!empty($_REQUEST["check"])){
if(file_exists('../iConnect/node.php')){
$readFile = file_get_contents('../iConnect/node.php');
$dataTxt = unserialize($readFile);
extract($dataTxt);
try{
$dbConnect = new PDO('mysql:host='.$dbHost.';dbname='.$dbName,$dbUser,$dbPass);
$dbConnect -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected";
}catch(PDOException $ex){
echo "ERROR: ".$ex->getMessage();
exit();
}
}else{
echo "File missing";
}
}
The creatCofig() code.
function createConfig(){
var dbUser = document.getElementById("dbUser").value,
dbPass = document.getElementById("dbPass").value,
dbName = document.getElementById("dbName").value,
dbHost = document.getElementById("dbHost").value;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","./bin/config/createConfig.php?dbUser="+dbUser+"&dbPass="+dbPass+"&dbName="+dbName+"&dbHost="+dbHost,true);
xmlhttp.send();
}
I know I'm missing something with the AJAX but my knowledge is limited on AJAX can some one please show me what am I doing wrong.
The complete callback has a signature of (jqXHR jqXHR, String textStatus).
Read about it here here.
Try the following pattern :
$.ajax({
url: ...,
type: ...,
data: ...,
dataType: ...,
}).then(function (data) {
alert(data.responseText);
});
Also, don't rely on a timeout to wait for an ajax response. That's what promises are for.
In createConfig(), use jQuery.ajax() and return a promise as follows :
function createConfig() {
return $.ajax({
'type': 'post',
'url': './bin/config/createConfig.php',
'data': {
'dbUser': $("#dbUser").val(),
'dbPass': $("#dbPass").val(),
'dbName': $("#dbName").val(),
'dbHost': $("#dbHost").val()
}
}).then(function(response) {
$("#response").html(response);
return response;
});
}
Now you can write :
if (noEmpty && confirm('Are you sure all details to be true?')) {
createConfig().then(checkResponse);
}

Jquery Ajax function is not working while calling the Servlet

I am facing some problem while calling ajax. Can anyone look at my code and suggest something to solve my problem
function search(file,input){
$.ajax({url:'/Searchandhighlight?name='+input+'&file='+file,type:"post",
success:function(){
$("#bodyy").html();
}
});
}
I am using ajax to call the servlet and servlet changes some contents of database and after success I am trying to refresh my "#bodyy" div.
Thanks in advance
Firstly let us know what file variable holds.
Normally Ajax call with parameters goes like this. dataType depends on what kind of response you are expecting.
$.ajax({
type: "POST",
url: "/Searchandhighlight",
dataType: "json",
data: {"name" : input, "file" : file},
success:function(data){
if(data){
alert("success");
}
},
error:function(){
alert('failed');
}
})
I finally solved my issue by following code
function search(file,input){
if(input != "") {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Searchandhighlight?name=" + input + "&file=" + file, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location.reload();
}
}
xmlhttp.send(null);
}
}

Making an API call in Javascript - new call at each click

Here's what I want to achieve:
I have an element on a webpage, let's call is storm
Every time the user clicks on the storm link, I want the following:
perform an API call which parameters are pre-defined BUT with the storm string as one of them
store the result (the API generates a JSON file) somewhere
parse the result with one method or another.
I have no problem parsing the JSON returned, but I would like to know how to do the first two steps.
NB: I use JS more than jQuery, but I'm not nazi on this.
Thank you very much for your help.
EDIT: thanks #ema
I've got a XHR model, attached under here.
Can you help me identify where I have to add my API url (from what I've understood, what is before the first question mark), and how to add to it the pre-defined parameters and the custom parameter (a string, containing storm for example)?
Thanks again
function XHR(url, method, data, onsuccess, onfailure, onprogress, onload, onabort) {
var request = new XMLHttpRequest();
// Ten seconds is ought to be enough for anybody.
var xhrtimeout = setTimeout(onfailure, 10000);
request.addEventListener("progress", onprogress, false);
request.addEventListener("load", onprogress, false);
request.addEventListener("error", onfailure, false);
request.addEventListener("abort", onabort, false);
request.addEventListener("readystatechange", function (e) {
if (request.readyState == 4) {
if (request.status == 200) {
clearTimeout(xhrtimeout);
onsuccess(request.responseText);
} else {
onfailure(e);
}
}
});
request.open(method, url, true);
request.send(data);
}
function getJSONAndParse(url, allDone) {
XHR(url, "GET", null, function(data) {
allDone(JSON.parse(data));
}, function() {
alert("error");
});
}
getJSONAndParse("http://lalala.com/json", function(parsedJSON) {
alert(parseJSON[0].name);
console.log(parseJSON);
});
You can use XMLHttpRequest, something like this:
var r = new XMLHttpRequest();
r.open("POST", "api/url", true);
r.onreadystatechange = function () {
var json = r.responseText;
// parse your json here
};
r.send("storm=value_of_storm&another_param=value_of_whatever");
HTH
Let me see if I understood..
To call an API from JQuery is very simple, and you cand use $.ajax (most complete) or $.post (simplest)
both you call on the click event that you can bind in $(document).ready with
$(document.ready(function(){
$('.mybuttons').off('click');//to only hit once if you have Postbacks
$('.mybuttons').on('click', myapicall);
});
example with $.ajax:
function myapicall(){
$.ajax({
beforeSend: function () {
// a 'Loading'
},
type: 'POST',
url: 'URL-OF-API',
contentType: 'application/json; charset=utf-8',
data: { stormvalue: 'the sorm value you want to send to API'},
dataType: 'json',
success: function (json) {
try {
json = JSON.parse(json.d);
// now you have a json object to play with, and if its a string, then you can """save""" using eg. input hidden
} catch (ex) {
alert(ex);//show the error parsing json
}
},
error: function (xhr, ajaxOptions, thrownError) {
var r = jQuery.parseJSON(xhr.responseText);
alert(r); // show the error of callback
},
complete: function (json) {
alert('sucess!');
}
});
}
example with $.post
function myapicall(){
$.post('URL-OF-API', { stormvalue: 'the sorm value you want to send to API'},
function (json) {
try {
json = JSON.parse(json.d);
// now you have a json object to play with, and if its a string, then you can "save" using eg. input hidden
} catch (ex) {
alert(ex);//show the error parsing json
}
}
);
}
Hope I can help you, and sorry for bad english, ;-)

Javascript AJAX call to Jquery Call

In order to have my code written almost fully written in Jquery, I want to rewrite an AJAX call in Jquery.
It's a call from a webpage to a Tomcat servlet.
Similar code of my present situation:
var http = new XMLhttpRequest();
var url = "http://example.com/MessageController?action=send";
http.onreadystatechange = function ()
if (http.readyState == 4)
{
if (http.status == 200){ var response = http.responseText;}
else {/*code2*/}
};
http.async = false;
http.open("POST", url, true);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(string);
Which would be the best way to do this? .ajax or .post? Could you help me with some pseudo code to start this?
Use .ajax or (as you are using POST) .post:
$.ajax({
url: "http://example.com/MessageController",
type: "POST",
data: { action: "send", yourStringName: "something" },
async: false, // make sure you really need it
contentType:'application/x-www-form-urlencoded'
}).done(function(response) {
console.log(response);
});
It doesn't matter which one you use, because .post is shorthand for .ajax.
You can use jQuery post.
var url="MessageController"
$.post(url, { action : "send"} ,function(data){
//response from MessageController is in data variable
//code 1
alert(data)
}).error(function(){
alert("error"); //code 2
})
Assuming MessageController is some url in your domain and you are aware of the same origin policy

Categories

Resources